Mar*_*ery 24 python python-module python-import
当我开发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
我在这里描述的功能一样,但有没有一种简单的方法可以将这样的东西组合在一起?
小智 30
我遇到了同样的问题,你激励我真正解决问题.
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)
Run Code Online (Sandbox Code Playgroud)
或者,如果您正在使用IPython,只需使用dreload
或传递--deep-reload
启动.
我遇到了同样的问题,并且我已经建立了@Mattew 和@osa 的答案。
from types import ModuleType
import os, sys
def rreload(module, paths=None, mdict=None):
"""Recursively reload modules."""
if paths is None:
paths = ['']
if mdict is None:
mdict = {}
if module not in mdict:
# modules reloaded from this module
mdict[module] = []
reload(module)
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if type(attribute) is ModuleType:
if attribute not in mdict[module]:
if attribute.__name__ not in sys.builtin_module_names:
if os.path.dirname(attribute.__file__) in paths:
mdict[module].append(attribute)
rreload(attribute, paths, mdict)
reload(module)
#return mdict
Run Code Online (Sandbox Code Playgroud)
有以下三个区别:
实际编写一些测试用例并在每次完成模块修改后都运行它们会更简单吗?
您正在做的事情很酷(本质上是在使用TDD(测试驱动的开发),但是您做错了。
考虑到与写单元测试(使用默认的Python 单元测试模块,或者更好的鼻子)你有那些测试可重复使用的,稳定的,并帮助您检测inconsitencies在你的代码要多更快,更好比在交互式测试你的模块环境。
归档时间: |
|
查看次数: |
6477 次 |
最近记录: |