herhangi modülleri yeniden modülü inceleyerek derin yükleme işlevini uygulanması ve yeniden deneyebilirsiniz
kullanır. Bu kusursuz değildir, örneğin:
class MyClass:
module = import_module('amodule')
ancak sizin için yeterince iyi olabilir.
mymod.py yeni bir süreç başlatır veya her çoklu işlem işinin başında da kolay her
import importlib
import sys
import mymod
def deep_reload_module(name):
mod = sys.modules.get(name)
if not mod:
importlib.import_module(name)
return
def get_mods_to_reload_recursively(name, modules_to_reload=None):
modules_to_reload = modules_to_reload or set()
mod = sys.modules[name]
modules_to_reload.add(name)
# loop through the attributes in this module and remember any
# submodules we should also reload
for attr in dir(mod):
prop = getattr(mod, attr)
if isinstance(prop, type(mymod)):
modname = attr
elif hasattr(prop, '__module__'):
modname = prop.__module__
if not modname:
continue
else:
# this thing is not a module nor does it come from another
# module, so nothing to reimport.
continue
if modname in sys.builtin_module_names:
# probably best not to reimport built-ins...
continue
if modname in modules_to_reload:
# this is already marked for reimporting, so avoid infinite
# recursion
continue
# get_mods_to_reload... will update modules_to_reload so no need to
# catch the return value
get_mods_to_reload_recursively(modname, modules_to_reload)
return modules_to_reload
mods_to_reload = get_mods_to_reload_recursively(name)
for mtr in mods_to_reload:
# best to delete everything before reloading so that you are
# sure things get re-hooked up properly to the new modules.
print('del sys.modules[%s]' % (mtr,))
del sys.modules[mtr]
importlib.import_module(name)
if __name__ == '__main__':
orig_mymod_id = id(sys.modules['mymod'])
deep_reload_module('mymod')
assert orig_mymod_id != id(sys.modules['mymod'])
Sonra sadece deep_reload_module('module')
aramak zorunda
# Example submodule to re-import
print('import module mymod')
# demonstrate we can even import test as a module and it works
import sys
from test import deep_reload_module
value = 2
def a_function():
pass
class XYZ:
pass
class NewClass(object):
pass
test.py.
Not: bu o zaman varsa bu kod eski modülü kullanmak veya kırmaya devam edecek, çünkü daha önce bu modülün ithal şey olmamasından reimport istediğiniz modül dışında yaşayan koduna oldukça dayanır.
E.g. Eğer kodu var ise bunu yapar: modül reimported sonra sadece globals()
için zayıf bir başvuru tutar beri
from module_to_reimport import a_function
Ama her yerde açıkça module_to_reimport
muhafaza değil, o a_function
iyi denir aldığında başarısız olabilir module_to_reimport
'da tanımlanmıştır ve bunların tümü, modülü sys.modules
'dan silerek yok edilecektir.
Benzer konu, https://bytes.com/topic/python/answers/22688-multiple-instances-modules –
Teşekkürler Xin, ancak söz konusu modülün yanıtları söz konusu modülü yazdığınızı varsayar. Burada ele alınan, kötü yazılmış bir şey - sınıflar yerine modüllerde devlet ile. – er0