python是否多次加载模块?

2024-04-18 21:59:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我注意到一些奇怪的情况,如以下测试失败:

x = <a function from some module, passed around some big application for a while>

mod = __import__(x.__module__)
x_ref = getattr(mod, x.__name__)
assert x_ref is x  # Fails

(这样的代码出现在pickle模块中)

我想我没有任何导入钩子,重新加载调用,或者系统模块会扰乱python正常导入缓存行为的操作。你知道吗

一个模块被加载两次还有其他原因吗?我看到过关于这个的声明(例如,https://stackoverflow.com/a/10989692/1332492),但是我无法用一个简单的、孤立的脚本来重现它。你知道吗


Tags: 模块fromimportrefmodforapplication情况
1条回答
网友
1楼 · 发布于 2024-04-18 21:59:46

我相信你误解了^{}的工作原理:

>>> from my_package import my_module
>>> my_module.function.__module__
'my_package.my_module'
>>> __import__(my_module.function.__module__)
<module 'my_package' from './my_package/__init__.py'>

根据文件:

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

如您所见,__import__不返回子模块,而只返回top包。如果在包级别也定义了function,那么确实会有不同的引用。你知道吗

如果只想加载模块,应该使用^{}而不是__import__。你知道吗


至于回答您的实际问题:恐怕没有办法导入相同的模块,和相同的名称,两次而不搞乱导入机制。但是,包的子模块也可以在sys.path中使用,在这种情况下,您可以使用不同的名称导入它两次:

from some.package import submodule
import submodule as submodule2
print(submodule is submodule2)   # False. They have *no* relationships.

这有时会导致问题,例如pickle。如果对submodule引用的内容进行pickle,则不能使用submodule2作为引用来取消对其的pickle。你知道吗

但是,这并没有涉及您给我们的具体示例,因为使用__module__属性导入应该返回正确的模块。你知道吗

相关问题 更多 >