, , .
, . .
Py 2, 3. Python 2.7 Python 3.5.
import sys
__all__ = ["reload"]
try:
_reload = reload
from thread import get_ident
def reload (module):
if isinstance(module, basestring):
module = sys.modules[module]
if module.__name__==__name__:
raise RuntimeError("Reloading the reloading module is not supported!")
print ("Reloading: %s" % module.__name__)
ls = sys._current_frames()[get_ident()].f_back.f_locals
vars = [name for name, mod in ls.iteritems() if mod==module]
if len(vars)==0:
print ("Warning: Module '%s' has no references in this scope.\nReload will be attempted anyway." % module.__name__)
else:
print("Module is referenced as: %s" % repr(vars))
m = _reload(module)
for x in vars:
ls[x] = m
print("Reloaded!")
except NameError:
from _thread import get_ident
def reload (module):
if isinstance(module, str):
module = sys.modules[module]
if module.__name__==__name__:
raise RuntimeError("Reloading the reloading module is not supported!")
print ("Reloading: %s" % module.__name__)
ls = sys._current_frames()[get_ident()].f_back.f_locals
vars = [name for name, mod in ls.items() if mod==module]
if len(vars)==0:
print ("Warning: Module '%s' has no references in this scope.\nReload will be attempted anyway." % module.__name__)
else:
print("Module is referenced as: %s" % repr(vars))
for x in vars:
del ls[x]
del sys.modules[module.__name__]
m = __import__(module.__name__)
for x in vars:
ls[x] = m
for vname in dir(m):
setattr(module, vname, getattr(m, vname))
print("Reloaded!")
>>>
>>> from rld import *
>>> import math
>>> math.cos
<built-in function cos>
>>> del math.cos
>>> math.cos
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'cos'
>>> reload(math)
Reloading: math
Module is referenced as: ['math']
Reloaded!
>>> math.cos
<built-in function cos>
>>>
>>>
>>> import math as quiqui
>>> alias = quiqui
>>> del quiqui.cos
>>> quiqui.cos
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'cos'
>>> alias.cos
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'cos'
>>> reload("math")
Reloading: math
Module is referenced as: ['alias', 'quiqui']
>>> quiqui.cos
<built-in function cos>
>>> alias.cos
<built-in function cos>