如何导入PEP8包

7

如果我从第三方导入一个模块,但他们的语法与我的不一致,有没有好的方法来符合pep8规范?

例如:我需要使用一个无法编辑的第三方模块,他们的命名约定并不是很好。

示例:

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格式化?

1
只是好奇:您会如何应用那个 pepification 函数? - tobias_k
8
这似乎比它值得的麻烦多了...但是为什么不使用from third_party import fooBar_function as whatever_you_want呢? - deceze
@deceze 大约有100个函数需要导入,所以那不是一个真正的选择...我猜那只是最坏的情况下的选择。 - code base 5000
@tobias_k 这是我的问题。 - code base 5000
我猜你可以编写一个脚本,从一个模块中导入所有名称,将这些名称“pepifies”,并创建一个Python脚本,比如说pepified_third_party_module,其中每个名称都有一个from ... import ... as ...。然后,只需导入pepified模块而不是原始模块即可。 - tobias_k
你是否意识到你的_pep8ify现在无法适当地处理类? - Darkonaut
2个回答

6

您可以使用上下文管理器来自动将导入模块中的符号转换为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):
        # 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

0
我觉得像这样做可以实现你想要的功能:
# somemodule.py
def func_a():
    print('hello a')

def func_b():
    print('hello b')


# yourcode.py
import inspect
import importlib

def pepimports(the_module_name):
    mymodule = importlib.import_module(the_module_name)
    myfuncs = inspect.getmembers(f, inspect.isfunction)
    for f in myfuncs:
        setattr(mymodule, _pep8ify(f[1].__name__) , f[1])
    return mymodule

mymodule = pepimports('some_module_name')
# you can now call the functions from mymodule
# (the original names still exist, so watch out for clashes)
mymodule.pepified_function()

这个方法有点hackish,但我已经尝试过了(Python 3.5),它似乎可以工作(至少在一个简单的例子中)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接