您可以使用上下文管理器来自动将导入模块中的符号转换为pep8格式,例如:
示例:
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):
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
from third_party import fooBar_function as whatever_you_want
呢? - decezepepified_third_party_module
,其中每个名称都有一个from ... import ... as ...
。然后,只需导入pepified模块而不是原始模块即可。 - tobias_k_pep8ify
现在无法适当地处理类? - Darkonaut