`del` on a package has some kind of memory

邮差的信 提交于 2019-12-03 04:11:53

I would say that the package is still seen as imported. So performing import math again just redeclares the name, but with old contents.

You could use reload to make sure your module is whole again, except that some versions of python require to remove the entry in sys.modules as well, which makes the use of reload redundant:

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

(this difference between various python versions, reload and import are discussed in a follow-up question: Should importlib.reload restore a deleted attribute in Python 3.6?)

A package is only read from disk once and then stored in memory as mutable singleton. The second time you import it you get the exact same singleton you have previously imported, and it's still missing its cos. del math merely deletes the local name for it, it doesn't "unimport" the package from Python overall.

del math does not delete the package at all, it just deletes the local name math in the current module.

Like any other object, if any other references to the math module exist anywhere, then it's kept in memory.

And in particular, sys.modules is always a dictionary of all loaded modules, so at least there's always a reference there.

Edit: But there's a way to actually reload a module, imp.reload.

Unfortunately I can't get it to work for this case, reload needs the random module (probably to create some part of the compiled Python file), the random module needs math.cos, and it's gone. Even with importing random first there is no error, but math.cos doesn't reappear; I don't know why, maybe because it's a builtin module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!