不,reload
永远不会删除模块对象。它只是就地修改模块对象。因此,如果重新加载失败,旧绑定仍然保持不变。
http://docs.python.org/2/library/functions.html#reload
#so.py
i = 0
lis = [1,2,3]
dic = {"a":1, "b":2}
现在让我们导入这个模块:
>>> import so
>>> x = so.lis[0]
>>> so.lis[0]=0 #modify so.lis
>>> so.dic["a"] = so.lis #modify so.dic
>>> !rm -r so.py so.pyc #delete both so.py and so.pyc
>>> try: #try reloading
... reload(so)
... except ImportError:
... pass
...
>>> so.lis #previous binding are still intact
[0, 2, 3]
>>> x
1
>>> so.dic
{'a': [0, 2, 3], 'b': 2}
现在我们将尝试修改模块而不是删除:
#so.py
i = 0
lis = [1,2,3,4]
dic = {"a":1, "b":2}
现在导入它:
>>> import so
>>> lis = so.lis #add a new reference to it
>>> so.lis[0] = 0 #modify so.lis
>>> so.i
0
现在将 so.py 修改为:
#so.py
i = 0
lis = [1,2,3] #updated lis
dic = {"a":1, "b":2}
现在reload()
:
>>> reload(so)
<module 'so' from 'so.py'>
>>> so.lis #got updated
[1, 2, 3]
>>> lis #old so.lis object is still in memory as it's reference count is not 0
[0, 2, 3, 4]