当我开发 Python 代码时,我通常在解释器中以特别的方式对其进行测试。我会import some_module
,测试一下,找到bug,修复bug并保存,然后使用内置的reload
函数reload(some_module)
并再次测试。
但是,假设在 some_module
我有 import some_other_module
,并且在测试 some_module
时我发现 some_other_module
并修复它。现在调用 reload(some_module)
不会递归地重新导入 some_other_module
。我必须手动重新导入依赖项(通过执行 reload(some_module.some_other_module)
或 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
。
关于python - 'reload'的递归版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15506971/