python - 在 Python 中重新加载内置函数

标签 python python-3.x python-3.6 python-importlib built-in

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

相关文章:

python - PySpark:获取数据框中每列的第一个非空值

python - 可以导入 python 包,但不能导入其模块

python - 是否可以将 Python 中的所有类型提示/检查基础结构分离到 .pyi 文件中?

python - 为什么我的 Ubuntu 20.04 DEV 机器上安装了多个 Python 版本?

python - 我想要一个类' __init__ 将对象添加到列表中,但我想防止冗余并且 "if self not in objectlist"不工作

python - 定义类 : Module takes at most 2 arguments

python - 在 Python 中运行 C 扩展比普通 C 更快

python - 如何在 Python 正则表达式中匹配重复后的非字符

python - 从表中提取特定数据

python - 我有一个争论问题,但我不明白为什么?