`del` on the packet has some kind of memory

delI seem to have a memory that puzzles me. See the following:

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'

Fine Let's see what happens if we remove the entire math package:

In [5]: del math

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

NameError: name 'math' is not defined

So, now the math itself is gone, as expected.

Now import the math again:

In [7]: import math

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

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

So, somehow interactive python remembers that math.cos was specifically deleted even after we removed the entire math package and imported it again.

Where does python store this knowledge? Can we access it? Can we change it?

+42
source share
3 answers

I would say that the package is still considered imported. Therefore, execution import mathagain simply overrides the name, but with the old contents.

reload, , , , python sys.modules, reload :

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

( python, reload import : importlib.reload Python 3.6?)

+23

, singleton. , , , , - cos. del math , " " Python.

+62

del math , math .

, - , .

, , sys.modules , .

: , imp.reload.

Unfortunately, I can’t get it to work for this case, the reboot requires a random module (perhaps to create part of a compiled Python file), it takes a random module math.cos, and it disappeared. Even with import random, there is no error at first, but it math.cosdoes not appear again; I do not know why, maybe because it is a built-in module.

+15
source

Source: https://habr.com/ru/post/1693707/


All Articles