如何进口PEP8包装

2024-04-20 13:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

示例:

thisIsABase_function(self,a,b)

我有一些代码可以将名称pep8改为pep8,但我想知道如何使用新的pep8名称来访问函数?在

^{pr2}$

有没有办法让我把这些名字在进口上打上记号?在


Tags: 模块方法函数代码self名称编辑示例
2条回答

可以使用上下文管理器自动识别导入模块中的符号,例如:

示例:

with Pep8Importer():
    import funky

代码:

^{pr2}$

测试代码:

with Pep8Importer():
    import funky

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

在时髦.py

thisIsABase_function = 1

结果:

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

1
1

我想这样的事情能达到你想要的效果:

# 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),它似乎可以工作(至少在一个小例子上)。在

相关问题 更多 >