本文介绍了在交互式上删除了模块的功能。如何重新导入? importlib.reload没有帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ipython上删除了(package builtin)函数:

I've deleted a (package builtin) function on 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'

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

OK. But how do I reload the function? This didn't help:

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,但:

The above code works for me in Python 3.4 on Windows but the documentation for 3.6 states:

(所以也许我只是幸运)

(so maybe I was only "lucky")

所以可以肯定的是:

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

它仍然有效,你不要甚至需要重新加载。只需从缓存中移除&再次导入。

It still works, and you don't even need reload. Just remove from cache & import again.

如评论中所述,使用 reload 也可以,但是你需要更新给定的模块参考通过重新加载,而不仅仅重复使用缺少 cos 条目的旧版本:

As noted in comments, using reload also works, but you need to update the module reference given by reload, not just reuse the same old one with the cos entry missing:

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

这篇关于在交互式上删除了模块的功能。如何重新导入? importlib.reload没有帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 23:54