1

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

class Klass(object):

    def a(self, d={}):
        print d
        self.b(d)

    def b(self, d={}):
        import random
        print d
        d[str(random.random())] = random.random()

I assumed that every time I call c.a() without arguments, I got a fresh empty dict. However, this is what actually happens:

>>> c = Klass()
>>> c.a()
{}
{}
>>> c.a()
{'0.637151613258': 0.61491180520119226}
{'0.637151613258': 0.61491180520119226}
>>> c.a()
{'0.637151613258': 0.61491180520119226, '0.960051474644': 0.54702415744398669}
{'0.637151613258': 0.61491180520119226, '0.960051474644': 0.54702415744398669}
...

I don't really want to do some sort of lambda/iscallable thing. What is a good pattern to use here?

Of course, I figured out I decent way around the problem by the time I had started typing out the question. But, if anyone has a different pet way around this, I would love to hear.

Community
  • 1
  • 1
Skylar Saveland
  • 11,116
  • 9
  • 75
  • 91

1 Answers1

1

Could get a fresh, empty dict with:

    def a(self, d=None):
        if d is None:
            d = {}

The problem is well described here under Mutable Default Arguments.

Skylar Saveland
  • 11,116
  • 9
  • 75
  • 91