在 Django 模型上,我有一个递归函数。现在有一种情况,如果我有 3 个模型设置了循环引用,我的递归函数将不会停止!我想做的测试是这样的:
old_recursion_limit = sys.getrecursionlimit()
sys.setrecursionlimit(3) # I know that if I go more than 3 recursive levels deep, my code has failed
try:
obj.recusive_fn()
except RuntimeError, e:
print e # here I am hoping the only runtime error I will encounter is maximum recursion depth reached
sys.setrecursionlimit(oldlimit)
现在,运行时错误没有在我的 try/catch block 中被捕获,而是导致测试运行器崩溃。有什么想法吗?
最佳答案
我通常做的是创建一个深度参数,默认为 0,每次增加 1。如果超出该深度,我可以引发异常或以某种方式处理它。
def recursion(parent, depth=0):
if depth > 3: # whatever depth you don't want to exceed
parent.append('leaf!')
return # or raise an exception
lst = []
for i in range(5):
recursion(lst, depth+1)
parent.append(lst)
print recursion([])
注意这个答案独立于 Django;只是如何在通用 Python 中完成它。
关于python - 如何测试 python 中的递归函数不会永远持续下去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21026299/