gpt4 book ai didi

python - 如何导入 PEP8 包

转载 作者:太空狗 更新时间:2023-10-29 21:45:08 25 4
gpt4 key购买 nike

如果我从第 3 方导入模块,但他们使用的语法与我的不一致,有没有好的方法来 pep8 呢?

示例:我需要使用一个我无法编辑的第 3 方模块,而且它们的命名约定不太好。

例子:

thisIsABase_function(self,a,b)

我有一些代码将名称命名为 pep8,但我想知道如何让新的 pep8 名称可以访问这些函数?

def _pep8ify(name):
"""PEP8ify name"""
import re
if '.' in name:
name = name[name.rfind('.') + 1:]
if name[0].isdigit():
name = "level_" + name
name = name.replace(".", "_")
if '_' in name:
return name.lower()
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

有没有办法在导入时将这些名称 PEP8?

最佳答案

您可以使用上下文管理器自动对导入模块中的符号进行 pep8ify,例如:

示例:

with Pep8Importer():
import funky

代码:

class Pep8Importer(object):

@staticmethod
def _pep8ify(name):
"""PEP8ify name"""
import re
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

def __enter__(self):
# get list of current modules in namespace
self.orig_names = set(dir(sys.modules[__name__]))

def __exit__(self, exc_type, exc_val, exc_tb):
""" Pep8ify names in any new modules

Diff list of current module names in namespace.
pep8ify names at the first level in those modules
Ignore any other new names under the assumption that they
were imported/created with the name as desired.
"""
if exc_type is not None:
return
new_names = set(dir(sys.modules[__name__])) - self.orig_names
for module_name in (n for n in new_names if not n.startswith('_')):
module = sys.modules[module_name]
for name in dir(module):
pep8ified = self._pep8ify(name)
if pep8ified != name and not name.startswith('_'):
setattr(module, pep8ified, getattr(module, name))
print("In mModule: {}, added '{}' from '{}'".format(
module_name, pep8ified, name))

测试代码:

with Pep8Importer():
import funky

print(funky.thisIsABase_function)
print(funky.this_is_a_base_function)

funky.py

thisIsABase_function = 1

结果:

In module: funky, added 'this_is_a_base_function' from 'thisIsABase_function'

1
1

关于python - 如何导入 PEP8 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48503812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com