在 Python 中重新加载内置函数

Reloading builtins in Python

我正在探索 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.