2

I have this piece of code in python which I fail to understand as how are these functions maintain their state when encapsulated in class.

class Param(object):

def bad_append(self, item, l=[]):
    l.append(item)
    return l


p = Param()
print(p.bad_append(1))
print(p.bad_append(2))

pp = Param()
print(pp.bad_append(100))

Output

[1]
[1, 2]
[1, 2, 100]

I can't understand as why the output for pp is [1, 2, 100] instead of [100].

wayfare
  • 1,802
  • 5
  • 20
  • 37

1 Answers1

2

The issue you're encountering is a gotcha of Python, the default parameter of the function is a globally shared value. Let me suggest the following change:

def bad_append(self, item, l=None):
  l = l or []
  #rest of code...

By setting the default to None and then reassigning to any list, you'll avoid the shared state.

wheaties
  • 35,646
  • 15
  • 94
  • 131
  • Another gotcha is that the OP doesn't actually need to return l, or rather, if you return l, your original l value will still be changed because lists are mutable. – Michael Tamillow Jul 15 '19 at 16:03