I was hunting an odd bug in a python program of mine.

Here’s a condensed code snippet for explanation:

class odd:
        def __init__(self, a, b={}):
                self.b = b
                self.b["a"]=a

one = odd(1)
two = odd(2)
print one.b["a"]

That code looks reasonable, doesn’t it? The parameter “a” is required, but other parameters can be given in a hash. So what output would you expect?

The output is 2. The reason is as follows:

Python creates an empty hash, and b is a reference to this hash per default. To the same hash each time. So the code is basically equivalent to

class odd2:
        default_for_b_in_init = {}
        def __init__(self, a, b=default_for_b_in_init):
                self.b = b
                self.b["a"]=a

and not (as I had expected):

class odd3:
        def __init__(self, a, b=None):
                if not b: b = {}
                self.b = b
                self.b["a"]=a

Obviously, both behaviours make sense, and the python way is somewhat consequenter.

So be careful when using default values in functions!

Non-reference types such as integers are fine, so is None, and of course any outside objects you want to be the same for each call. Don’t assume the def statement will create any new object.

Even shorter example:

def test(a, b={}):
        print b
        b["a"]=a
test(1)
test(2)

will result in the output

{}
{'a': 1}

again there is only a single hash b.