web-dev-qa-db-fra.com

Python: profondeur maximale de récursivité dépassée

J'ai le code de récursivité suivant, à chaque nœud j'appelle SQL requête pour obtenir les nœuds appartiennent au nœud parent.

voici l'erreur:

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

Méthode que j'appelle pour obtenir des résultats 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();

En fait, la méthode ci-dessus ne me pose aucun problème, mais je la pose quand même pour donner un bon aperçu de la question.

Code de récursivité:

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

Appel de la fonction récursive

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();

Code pour imprimer le dictionnaire,

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

Si la récursion est trop profonde, je devrais recevoir l'erreur lorsque j'appelle ma fonction de récursivité, mais lorsque j'obtiens cette erreur lorsque j'imprime le dictionnaire.

78
add-semi-colons

Vous pouvez incrémenter la profondeur de pile autorisée - avec ceci, des appels récursifs plus profonds seront possibles, comme ceci:

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

... Mais je vous conseillerais d'abord d'essayer d'optimiser votre code, par exemple, en utilisant l'itération au lieu de la récursion.

155
Óscar López