Python: 超过了最大递归深度

我有以下递归代码,在每个节点上调用 sql query 来获取属于父节点的节点。

这里有一个错误:

Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879768c>> ignored


RuntimeError: maximum recursion depth exceeded while calling a Python object
Exception AttributeError: "'DictCursor' object has no attribute 'connection'" in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879776c>> ignored

调用以获取 sql 结果的方法:

def returnCategoryQuery(query, variables={}):
cursor = db.cursor(cursors.DictCursor);
catResults = [];
try:
cursor.execute(query, variables);
for categoryRow in cursor.fetchall():
catResults.append(categoryRow['cl_to']);
return catResults;
except Exception, e:
traceback.print_exc();

我实际上没有任何问题与上述方法,但我把它无论如何给予适当的概述的问题。

递归代码:

def leaves(first, path=[]):
if first:
for elem in first:
if elem.lower() != 'someString'.lower():
if elem not in path:
queryVariable = {'title': elem}
for sublist in leaves(returnCategoryQuery(categoryQuery, variables=queryVariable)):
path.append(sublist)
yield sublist
yield elem

调用递归函数

for key, value in idTitleDictionary.iteritems():
for startCategory in value[0]:
print startCategory + " ==== Start Category";
categoryResults = [];
try:
categoryRow = "";
baseCategoryTree[startCategory] = [];
#print categoryQuery % {'title': startCategory};
cursor.execute(categoryQuery, {'title': startCategory});
done = False;
while not done:
categoryRow = cursor.fetchone();
if not categoryRow:
done = True;
continue;
rowValue = categoryRow['cl_to'];
categoryResults.append(rowValue);
except Exception, e:
traceback.print_exc();
try:
print "Printing depth " + str(depth);
baseCategoryTree[startCategory].append(leaves(categoryResults))
except Exception, e:
traceback.print_exc();

打印字典的代码,

print "---Printing-------"
for key, value in baseCategoryTree.iteritems():
print key,
for elem in value[0]:
print elem + ',';
raw_input("Press Enter to continue...")
print

如果递归过深,那么在调用递归函数时就会出错,但是在打印字典时就会出错。

221723 次浏览

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.