Search code examples
pythondefault-parameters

Default parameters in Python


I have class hierarchy as follows:

class ContextSummary(object):
    def __init__(self, id, db):
        self.db = db
        self.id = id

class GroupContextSummary(ContextSummary):
    def __init__(self, gId, db = {}):
        super(GroupContextSummary, self).__init__(gId, db)

I use GroupContextSummary class without the 2nd parameter multiple times in unittest.

groupSummary = GroupContextSummary(gId)

The issue is that the db still keeps the previous run values. In order to prevent this, I had to use

groupSummary = GroupContextSummary(gId, {})

Or I had to redefine the init method as

def __init__(self, gId, db = None):
    if db is None: db = {}
    super(GroupContextSummary, self).__init__(gId, db)

What might be wrong?


Solution

  • Whenever you pass a mutable object into a function, you should immediately make a copy of it if you're going to make any changes to the contents. That's true not just for __init__ but for any function. It's also true if the argument doesn't even have a default.

    You should replace the line in ContextSummary to:

    self.db = db.copy()
    

    I'm assuming that you didn't intend to modify the object you passed in. If the intent of the function is to modify its parameter, then it doesn't make sense for it to have a default does it?