0

This is really odd - I have 11 labels being passed into LabelTree. The first time I call sort_by_hierarchy, everything is fine.

I refresh the page, an AJAX call gets shot off to call this function, and then it returns 22 labels. I refresh the page again, 44 labels.

What am I doing wrong?

class LabelTree:
    def __init__(self, labels):
        self.by_parent = {}
        self.by_id = {}

        for label in labels:
            parent_id = 0 if label.parent_id is None else label.parent_id

            if parent_id not in self.by_parent:
                self.by_parent[parent_id] = []

            self.by_parent[parent_id].append(label)
            self.by_id[label.id] = label

    def sort_by_hierarchy(self, parent_id=0, depth=0, hierarchical_labels=[]):
        if parent_id not in self.by_parent:
            return hierarchical_labels

        labels = self.by_parent[parent_id]

        for label in labels:
            label.depth = depth
            hierarchical_labels.append(label)

            hierarchical_labels = self.sort_by_hierarchy(label.id, depth+4, hierarchical_labels)

        return hierarchical_labels
Kerry Jones
  • 21,806
  • 12
  • 62
  • 89

1 Answers1

2

The problem is in:

def sort_by_hierarchy(self, parent_id=0, depth=0, hierarchical_labels=[]):

Never create arguments with default values like [] or {} because the list or dict will be created only once and the next invocation of your method will have the modified version (with former labels inside) of the list as default value for hierarchical_labels.
Use this idiom instead:

def sort_by_hierarchy(self, parent_id=0, depth=0, hierarchical_labels=None):
    if hierarchical_labels is None:
        hierarchical_labels = []
ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
  • 2
    Also, see [here](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments) or [here](http://stackoverflow.com/questions/1132941/) for an explanation. – Jorge Leitao Jun 05 '14 at 09:23