0

What should the following code print?

class C:
    def b(self,d = {'k':0}):
        print(d)
        d['k'] += 1
    def a(self):
        self.b()
c1 = C()
for i in range(3):
    c1.a()

I could have sworn it should be

{'k': 0}
{'k': 0}
{'k': 0}

since I am calling b self.b() without any parameters so it should pick the default value of d each time which is {'k':0}. I just don't know what I am overlooking here but it prints

{'k': 0}
{'k': 1}
{'k': 2}

What is wrong with the following two statements?

  1. It should pick the default value of d when b is called without arguments
  2. d should be local to the method b and should not persist between different calls to the method b
figs_and_nuts
  • 4,870
  • 2
  • 31
  • 56
  • default values are evaluated *once* at function defintion time. It re-uses the *same object*, however, your method *mutates* that object, so of course, on another invocation, that change will be visible (because it is the same object) – juanpa.arrivillaga Apr 19 '23 at 18:14
  • Also relevant: https://stackoverflow.com/questions/26320899/why-is-the-empty-dictionary-a-dangerous-default-value-in-python and its duplicate target https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument. – Marijn Apr 19 '23 at 18:22
  • I've been on Python for about a couple of years now. I wonder how I survived without knowing something so basic. Thank you for the help guys. Keep rocking!! – figs_and_nuts Apr 19 '23 at 18:24

0 Answers0