我正在探索 Python 中命名空间的概念,但我无法解释以下内容:重新加载 builtins
并不能有效地重新加载模块。这是一个例子:
import importlib as il
import os
import mymodule
mymodule.x = 6
print(mymodule.x)
mymodule = il.reload(mymodule)
print(mymodule.x)
import builtins
builtins.print = lambda x : os.system('echo hello')
builtins.print('hi')
builtins = il.reload(builtins)
builtins.print('hi')
其中 mymodule 仅包含赋值 x = 5
。输出为:
6
5
hello
hello
也许这是一个虚拟问题,但是这种行为的原因是什么?
最佳答案
来自docs :
It is generally not very useful to reload built-in or dynamically loaded modules. Reloading
sys
,__main__
,builtins
and other key modules is not recommended. In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded.
关于python - 在 Python 中重新加载内置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42798340/