Question

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?

Was it helpful?

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?

OTHER TIPS

Common problem with defaults in python. Defaults get assigned at function definition time, not when the function is called. One solution is to do this:

def func(a, b=None):
    if not b:
        b = {}

Obviously, if None is a legitimate argument for b, you don't want to use None as the default for b. Whoops. You already knew that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top