Should importlib.reload recover a deleted attribute in Python 3.6?

I consider the following two related questions: here and here .

I see a behavior that I do not expect in Python 3.6, which is different from the behavior using plain reloadin Python 2.7 (and 3.4). Namely, it seems that the attribute of the module, which will be filled during module initialization or when the module is executed again during reboot, is not restored after deleting the local name with del... see below:

For Python 3.6:

In [1]: import importlib

In [2]: import math

In [3]: del math.cos

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

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

In [5]: math = importlib.reload(math)

In [6]: math.cos
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-05b06e378197> in <module>()
----> 1 math.cos

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

In [7]: importlib.reload(math)
Out[7]: <module 'math' from '/home/ely/anaconda/envs/py36-keras/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>

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

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

For Python 2.7 (and Python 3.4 ):

In [1]: import math

In [2]: del math.cos

In [3]: math.cos
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-05b06e378197> in <module>()
----> 1 math.cos

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

In [4]: reload(math)
Out[4]: <module 'math' from '/home/ely/anaconda/lib/python2.7/lib-dynload/math.so'>

In [5]: math.cos
Out[5]: <function math.cos>

importlib exec C, , cos dict .

, - C, , (, , , , , ), exec (, cos), , Python 2.7.

+4
1

, (? ?) PEP 489, . PEP :

importlib.reload() , , .

- ( dlopen POSIX, LoadModuleEx Windows), , .

, , . , .

, , , , commit, PEP 489.

Python 3.4 ; dict , dict . , , , - . , .

+2

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


All Articles