删除了交互式模块的功能。如何重新导入?importlib.reload没有帮助


问题内容

我已经在ipython上删除了(内置软件包)函数:

Python 3.6.4 |Anaconda custom (64-bit)| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import math

In [2]: math.cos(0)
Out[2]: 1.0

In [3]: del math.cos

In [4]: math.cos(0)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-9cdcc157d079> in <module>()
----> 1 math.cos(0)

AttributeError: module 'math' has no attribute 'cos'

好。但是,如何重新加载该功能?这没有帮助:

In [5]: import importlib

In [6]: importlib.reload(math)
Out[6]: <module 'math' (built-in)>

In [7]: math.cos(0)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-9cdcc157d079> in <module>()
----> 1 math.cos(0)

AttributeError: module 'math' has no attribute 'cos'

问题答案:

上面的代码对我来说适用于Windows上的Python
3.4,但3.6的文档指出:

但是要当心,就像您保留对模块对象的引用一样,在sys.modules中使它的缓存条目无效,然后重新导入命名模块,这两个模块对象将是不同的。相比之下,importlib.reload()将重用相同的模块对象,并通过重新运行模块的代码来简单地重新初始化模块内容。

(所以也许我只是“幸运”)

因此,可以肯定的是:

import math,sys
del math.cos
del math
sys.modules.pop("math")   # remove from loaded modules
import math
print(math.cos(0))

它仍然有效,您甚至不需要reload。只需从缓存中删除并再次导入即可。

如注释中所述,使用reload也可以,但是您需要更新给出的模块引用reload,而不仅仅是重复使用cos缺少条目的旧模块:

import math,sys
del math.cos
import importlib
math = importlib.reload(math)
print(math.cos(0))