【问题标题】:Is there any way to import python modules for an entire package?有没有办法为整个包导入 python 模块?
【发布时间】:2017-06-12 14:44:58
【问题描述】:

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

├── 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 包中的文件默认具有这些导入?

【问题讨论】:

标签: python python-3.x import packages


【解决方案1】:

简而言之,不,没有办法让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 *,我建议您只需在每个文件的开头包含这几行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 2023-04-11
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多