标签:python-3-x ipython python-importlib python
我已经在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的documentation表示:
Beware though, as if you keep a reference to the module object, invalidate its cache entry in sys.modules, and then re-import the named module, the two module objects will not be the same. By contrast, importlib.reload() will reuse the same module object, and simply reinitialise the module contents by rerunning the module’s code.
(所以也许我只是“幸运”)
所以可以肯定的是:
import math,sys
del math.cos
del math
sys.modules.pop("math") # remove from loaded modules
import math
print(math.cos(0))
它仍然有效,您甚至不需要重新加载.只需从缓存中删除&再次导入.
如评论中所述,使用reload也可以,但是您需要更新reload给出的模块引用,而不仅仅是重用cos条目丢失的旧模块:
import math,sys
del math.cos
import importlib
math = importlib.reload(math)
print(math.cos(0))
标签:python-3-x,ipython,python-importlib,python 来源: https://codeday.me/bug/20191109/2012905.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。