Python 3.x 如何递归地导入模块中的所有类?

Python 3.x 如何递归地导入模块中的所有类?,python-3.x,module,Python 3.x,Module,是否可以递归地使用\uuuuuu all\uuuuuu? 这将导入\uuuu all\uuuu中的模块 from mypkg import * 但不是递归的 试图将所有内容放入\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu from pathlib import Path # List all python (.py) files in the c

是否可以递归地使用
\uuuuuu all\uuuuuu
? 这将导入
\uuuu all\uuuu
中的模块

from mypkg import *
但不是递归的

试图将所有内容放入
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

from pathlib import Path

# List all python (.py) files in the current folder and put them as __all__
fs = [f for f in Path('mypkg/').rglob('*.py') if not f.name.endswith('__init__.py')]
__all__ = [str(f).replace('/','.')[:-3][5:] for f in fs]
因为

from mypkg import *

AttributeError中的结果:对于包中的第一个文件夹,模块“mypkg”没有属性“module1.file1”

通过将该属性添加到
\uuu init\uuuuuuuuuuuy.py
中解决。对于大多数情况,这可能不是最好的方法,但对于我的用例来说已经足够好了

from pathlib import Path

# Include all classes when 'from mypkg import *' is called. 
fs = [f for f in Path('mypkg').rglob('*.py') if not f.name.startswith('_')]

for f in [str(f).replace('/', '.')[:-3] for f in fs]:
    statement = f'from {f} import *'
    exec(statement)