1

I'm trying to make a tree that has a recursive 'printAll' method.

My code is:

class Node(object):
    def __init__(self, children=[], tag=None):
        self.children = children
        self.tag = tag

    def appendChild(self, child):
        self.children.append(child)

    def getChildren(self):
        return self.children

    def printAll(self):
        print self.getChildren()
        for child in self.children:
            child.printAll()

And when I run it I get this: "maximum recursion depth exceeded while calling a Python object".

I'm guessing it has something to do with passing the top level scope down to the child when calling the child's printAll() method, causing an infinite loop. Any help is much appreciated.

distorteddisco
  • 249
  • 2
  • 10
  • possible duplicate of ["Least Astonishment" in Python: The Mutable Default Argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) – wim Feb 20 '13 at 01:46

1 Answers1

2

Try changing your default children:

class Node(object):
    def __init__(self, children=None tag=None):
        self.children = children if children is not None else []
        self.tag = tag

    def appendChild(self, child):
        self.children.append(child)

    def getChildren(self):
        return self.children

    def printAll(self):
        print self.getChildren()
        for child in self.children:
            child.printAll()

You might have a case of the "mutable default argument"

Community
  • 1
  • 1
askewchan
  • 45,161
  • 17
  • 118
  • 134