python’s default argument values

I’ve been trying to track down a bug for a couple days now with zmugfs. I’m caching the tree structure returned by smugmug.users.getTree. Here’s my Node class:

class Node(object):
    def __init__(self, path, inode=MyStat(), children=[]):
        self.path = path
        self.inode = inode
        self.children = children

To a newbie like me, this looks perfectly fine. If no inode is passed in create an instance of MyStat(), if no children are passed in create an empty list. Well guess what! That’s not how python works with lists. If you do what I did above the children list is shared! Imagine my horror when each Node has a reference to ALL of the children of the other Nodes. EEK! A few minutes of googling and I found this page:
4.7.1 Default Argument Values.

I changed the constructor of the Node class to be as follows:

def __init__(self, path, inode=MyStat(), children=None):
    self.path = path
    self.inode = inode
    if children is None:
        self.children = []
        self.children = children

This fixed my problem.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s