Python:如何从dir中的所有模块导入? [英] Python: how to import from all modules in dir?
问题描述
目录结构:
main.py
my_modules/
module1.py
module2.py
module1.py:
module1.py:
class fooBar():
....
class pew_pew_FooBarr()
....
...
如何将所有类从module *添加到没有前缀的main(即使用它们像foo = fooBar(),不是foo = my_modules.module1.fooBar())。
How can I add all classes from module* to main without prefixes (i.e. to use them like foo = fooBar(), not foo = my_modules.module1.fooBar()).
一个明显的决定是在main.py中写这样的东西:
An obvious decision is to write in main.py something like this:
from my_modules.module1 import *
from my_modules.module2 import *
from my_modules.module3 import *
...
但我不想在创建新模块N时更改main.py.有解决方案吗?
But I don't want to change main.py when I create new moduleN. Is there solution for that?
我知道导入这样的类不是一个好主意,但我仍然对此感到好奇。
I do know it's not a good idea to import classes like this, but I'm still curious about that.
UPD:这个问题与此不同将所有模块加载到Python中的文件夹中,因为我的问题是加载没有命名空间的模块。
UPD: This question differs from this one Loading all modules in a folder in Python, because my problem is to load modules without namespaces.
推荐答案
In my_modules
文件夹,添加 __ init __。py
文件,使其成为正确的包。在该文件中,您可以在 __ init __。py
文件的全局范围内注入每个模块的全局变量,这使得它们在您导入模块时可用(在您之后)我还在 __ all __
变量中添加了全局名称:
In the my_modules
folder, add a __init__.py
file to make it a proper package. In that file, you can inject the globals of each of those modules in the global scope of the __init__.py
file, which makes them available as your module is imported (after you've also added the name of the global to the __all__
variable):
__all__ = []
import pkgutil
import inspect
for loader, name, is_pkg in pkgutil.walk_packages(__path__):
module = loader.find_module(name).load_module(name)
for name, value in inspect.getmembers(module):
if name.startswith('__'):
continue
globals()[name] = value
__all__.append(name)
现在,而不是:
from my_modules.class1 import Stuff
您可以这样做:
from my_modules import Stuff
或者将所有内容导入全局范围,这似乎是你想要做的:
Or to import everything into the global scope, which seems to be what you want to do:
from my_modules import *
这种方法的问题是类会相互覆盖,所以如果两个模块提供 Foo
,只能使用最后导入的那个。
The problem with this approach is classes overwrite one another, so if two modules provide Foo
, you'll only be able to use the one that was imported last.
这篇关于Python:如何从dir中的所有模块导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!