Python:如何从目录中的所有模块导入? [英] 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 *
...
但是我不想在创建新的 moduleN 时更改 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.
推荐答案
在 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:如何从目录中的所有模块导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!