假设我有一个 python 包 my_package
,其中包含一个模块 my_module
,其中包含一个函数 my_function
。
我试图在 python 交互式 shell 中执行以下导入:
>>> from my_package import my_module
>>> my_module.my_function() # => OK
>>> from my_module import my_function # => ImportError: No module named my_module
>>> from my_package.my_module import my_function # => OK
我对上面第三行的 ImportError
感到非常惊讶:既然 my_module
已经导入,为什么我不能从中导入函数?也许我对 python 导入系统的工作原理有一些误解,任何澄清将不胜感激!
这是目录结构和源代码。
my_package
|- __init__.py
|- my_module.py
这是__init__.py
文件
all = ["my_module"]
这是my_module.py
文件
def my_function():
pass
最佳答案
Python 导入系统不是这样工作的。当您执行 from foo import bar
时,foo
必须是“真实的”、完全限定的包或模块名称(或使用点的相对名称)。也就是说,它必须是可以在普通 import foo
中使用的东西。它不能只是你周围的一个模块对象。例如,您也不能这样做:
import foo as bar
from bar import someFunction
这在 the documentation 中有说明。 ,尽管您必须通读该部分才能了解完整情况。它说:
Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The statement comes in two forms differing on whether it uses the
from
keyword. The first form (withoutfrom
) repeats these steps for each identifier in the list. The form withfrom
performs step (1) once, and then performs step (2) repeatedly.
步骤 (1) 是“查找模块”,如果您继续阅读,您会发现这是在 sys.modules
、sys.path
中查找的过程。 code> 等。它没有必要在导入 namespace 中查找恰好具有模块对象作为其值的名称。请注意,两种导入的模块查找过程没有什么不同;当您执行 import foo
时,它查找 foo
的方式与您执行 from foo import bar
时查找它的方式相同。如果普通的 import my_module
不起作用(如您的示例所示),那么 from my_module import stuff
也不起作用。
请注意,如果您已经导入了模块并且只想为其中的函数使用较短的名称,则可以为该函数分配一个常规变量:
from my_package import my_module
myfunc = my_module.my_function
关于Python:从已导入的模块导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27830262/