如何在Python中单独导入一个子模块?

How to import a submodule alone in Python?

我有这个结构:

.
└── module
    ├── __init__.py
    └── submodule
        ├── __init__.py
        ├── foo.py
        └── bar.py

module.submodule.__init__.py 我有这个:

import foo
import bar

module.submodule.foo.py 我有这个:

import very_heavy_third_party_module as vhtpm
...

我只想导入 bar,但我被 foo 拖慢了速度(假设 foo 和 [= 中都有一个丑陋的 time.sleep(3) 21=]).

所以我的目标是在不被模块的其他部分拖慢速度的情况下将其写在下面:

from module.submodule.bar import saybar
saybar()

如何只导入位于我的子模块 bar 中的 saybar

在没有 运行 宁 foo 的情况下从 bar 导入的唯一方法是从 module.submodule.__init__.py 中删除 import foo。这是因为当您在 Python 中导入 package/module 时,该模块中的所有顶级代码(或者 __init__.py 如果导入包)都是 运行。当你运行from module.submodule.bar import saybar时,所有顶层代码在:

  • module.__init__.py
  • module.submodule.__init__.py
  • module.submodule.bar.py

是运行。由于 module.submodule.__init__.py 包含 import foofoo 被导入并且其所有顶级代码(包括 import very_heavy_third_party_module as vhtpm)也为 运行,导致速度变慢。

一些可能的解决方案是:

  • __init__.py 中移出尽可能多的代码。将 __init__.pys 留空是一种常见的做法 - 如果其中有一些功能,您可能需要考虑将其移动到自己的模块中。一旦 import 行是唯一剩下的行,您就可以删除它们,因为它们在命名空间方面没有区别。
  • foo.py 中的 import vhtpm 从顶层向下移动(例如,放入由模块中的其他内容调用的函数)。这不是很干净,但如果您需要优化,可能对您有用。