2
我剛剛認識到,imp.reload()
不刪除舊的類和函數,如果它們從模塊的源文件中刪除。爲什麼python的imp.reload()不會刪除舊的類和函數?
爲例:
:~$ 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'>
在最後幾行可以看到,有一類對象A
雖然它是從模塊的源代碼被刪除。這是爲什麼?有沒有辦法識別模塊的這些元素?