I just recognized that imp.reload() does not delete old classes and functions if they were deleted from the module’s source file.
An Example:
:~$ python3
Python 3.2.3 (default, May 3 2012, 15:54:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print(open("test.py").read())
# empty file
>>> import test
>>> dir(test)
['__builtins__', '__cached__', '__doc__', '__file__', '__name__',
'__package__']
>>> print(open("test.py").read())
# new class A and B added
class A:
pass
class B:
pass
>>> import imp
>>> dir(imp.reload(test))
['A', 'B', '__builtins__', '__cached__', '__doc__', '__file__', '__name__',
'__package__']
>>> print(open("test.py").read())
# class A deleted
class B:
pass
>>> dir(imp.reload(test))
['A', 'B', '__builtins__', '__cached__', '__doc__', '__file__', '__name__',
'__package__']
>>> import sys
>>> dir(sys.modules['test'])
['A', 'B', '__builtins__', '__cached__', '__doc__', '__file__', '__name__',
'__package__']
>>> sys.modules['test'].A
<class 'test.A'>
In the last lines you can see that there is a class object A although it was deleted from the modules source code. Why is this so? Is there a way to recognize such elements of a module?
According to the documentation:
So that’s why. If you don’t want those old objects there you can probably empty the module’s dictionary before reloading. For example, here I will import
hashlib, empty its dictionary, and reload it.Poor
hashlib.