Python:如何从目录中的所有模块导入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16852811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:48:36  来源:igfitidea点击:

Python: how to import from all modules in dir?

pythonimportmodule

提问by ov7a

Dir structure:

目录结构:

main.py
my_modules/
   module1.py
   module2.py

module1.py:

模块1.py:

class fooBar():
    ....
class pew_pew_FooBarr()
    ....
...

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()).

如何在没有前缀的情况下将 module* 中的所有类添加到 main(即像 foo = fooBar() 一样使用它们,而不是 foo = my_modules.module1.fooBar())。

An obvious decision is to write in main.py something like this:

一个明显的决定是在 main.py 中编写如下内容:

from my_modules.module1 import *
from my_modules.module2 import *
from my_modules.module3 import *
...

But I don't want to change main.py when I create new moduleN. Is there solution for that?

但是我不想在创建新的 moduleN 时更改 main.py。有解决方案吗?

I do know it's not a good idea to import classes like this, but I'm still curious about that.

我知道导入这样的类不是一个好主意,但我仍然对此感到好奇。

UPD: This question differs from this one Loading all modules in a folder in Python, because my problem is to load modules without namespaces.

UPD:这个问题不同于在 Python 中加载文件夹中的所有模块,因为我的问题是加载没有命名空间的模块。

采纳答案by Blender

In the my_modulesfolder, add a __init__.pyfile 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__.pyfile, which makes them available as your module is imported (after you've also added the name of the global to the __all__variable):

my_modules文件夹中,添加一个__init__.py文件,使其成为一个合适的包。在该文件中,您可以在文件的全局范围内注入每个模块的全局变量__init__.py,这使得它们在导入模块时可用(在您还将全局名称添加到__all__变量之后):

__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)

Now, instead of doing:

现在,而不是做:

from my_modules.class1 import Stuff

You can just do:

你可以这样做:

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 *

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.

这种方法的问题是类会相互覆盖,因此如果两个模块提供Foo,您将只能使用最后导入的一个。