当我开发 Python 代码时,我通常会在解释器中以临时方式对其进行测试。患病的import some_module
,测试一下,发现bug,修复bug并保存,然后使用内置的reload
功能为reload(some_module)
并再次测试。
然而,假设在some_module
I have import some_other_module
,并且在测试时some_module
我发现一个错误some_other_module
并修复它。现在打电话reload(some_module)
不会递归地重新导入some_other_module
。我必须手动重新导入依赖项(通过执行类似的操作reload(some_module.some_other_module)
, or import some_other_module; reload(some_other_module)
,或者,如果我更改了一大堆依赖项并且忘记了需要重新加载的内容,那么我需要重新启动整个解释器。
如果有一些就更方便了recursive_reload
功能,我可以做recursive_reload(some_module)
并且Python不仅重新加载some_module
,而且还递归地重新加载每个模块some_module
导入(以及每个模块导入的每个模块,等等),这样我就可以确定我没有使用其上的任何其他模块的旧版本some_module
依靠。
我认为 Python 中没有内置任何东西,其行为类似于recursive_reload
我在这里描述的功能,但是有没有一种简单的方法可以将这样的东西组合在一起?
我遇到了同样的问题,你激励我真正解决这个问题。
from types import ModuleType
try:
from importlib import reload # Python 3.4+
except ImportError:
# Needed for Python 3.0-3.3; harmless in Python 2.7 where imp.reload is just an
# alias for the builtin reload.
from imp import reload
def rreload(module):
"""Recursively reload modules."""
reload(module)
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if type(attribute) is ModuleType:
rreload(attribute)
或者,如果您使用的是 IPython,只需使用dreload
或通过--deep-reload
启动时。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)