首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何导入PEP8包

如何导入PEP8包
EN

Stack Overflow用户
提问于 2018-01-29 22:40:41
回答 2查看 787关注 0票数 7

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

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

示例:

代码语言:javascript
复制
thisIsABase_function(self,a,b)

我有一些代码可以将这个名称转换为pep8,但是我想知道如何才能用这个新的pep8名称访问这些函数?

代码语言:javascript
复制
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这些名字?

EN

回答 2

Stack Overflow用户

发布于 2018-02-05 05:42:03

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

示例:

代码语言:javascript
复制
with Pep8Importer():
    import funky

代码:

代码语言:javascript
复制
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))

测试代码:

代码语言:javascript
复制
with Pep8Importer():
    import funky

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

funky.py

代码语言:javascript
复制
thisIsABase_function = 1

结果:

代码语言:javascript
复制
In module: funky, added 'this_is_a_base_function' from 'thisIsABase_function'

1
1
票数 6
EN

Stack Overflow用户

发布于 2018-02-05 04:53:01

我认为这样的东西就是你想要的:

代码语言:javascript
复制
# 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()

它有点老套,但我已经尝试过了(python3.5),看起来还不错(至少在一个简单的例子中是这样)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48503812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档