python - 有没有办法为整个包导入 python 模块?

标签 python python-3.x import package

我有一个看起来像这样的包结构

├── Plugins
│   ├── Eight_Ball.py
│   ├── Ping.py
│   ├── Weather.py
│   ├── __init__.py

包中的每个 .py 文件都需要从项目的其他地方导入一些模块。我宁愿包中的每个文件都不以

开头
from ..Utils.constants import Plugin_Type
from ..Models.Plugin import Plugin
from ..Models.Singleton import Singleton

那么有没有办法让 Plugins 包中的文件默认具有这些导入?

最佳答案

简而言之,不,没有办法让 Plugins 包中的文件默认导入东西。

虽然通常不鼓励使用 from module import *,但如果您真的想保存那几行额外的行,您可以制作一个通用导入文件,导入您需要的所有内容,如下所示:

common_imports.py:

  from ..Utils.constants import Plugin_Type
  from ..Models.Plugin import Plugin
  from ..Models.Singleton import Singleton

other_files.py:

  from .common_imports import *

同样,不鼓励使用 from module import *,我建议您只在每个文件的开头包含这几行。

关于python - 有没有办法为整个包导入 python 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885155/

相关文章:

python - 需要静态时间 (X) 值以与 CPU 值 (Y) 匹配

python - 在 SQLAlchemy 中选择 NULL 值

python - 使多处理函数的装饰器超时

Python/Twisted 多用户服务器 - 哪个更高效?

python - 如何使用 Django Python 显示我最近的 3 篇文章

python - 如何确定正在运行的当前进程是否是父进程?

django - DRF APIView - 如何将帮助文本添加到自动生成的表单?

python - 使用 "."的相对导入在 python 中总是有意义吗?

python - IPython sys.path 不同于 python sys.path

sqlite - sqlite不在命令行中创建表