1
def foo(x, obj={}):
    obj['x'] = x
    return obj

values = []
for i in range(3):
    obj = foo(i)
    values.append(obj)
values = [v['x'] for v in values]
print(values)

In the above snippet code, I am not passing anything to the keyword arguemnt obj , so in my understanding it should get initialized with {} everytime and the final print statement should print [0, 1, 2].

However in actual, the value being passed is the last value created by foo function, i.e. the output I am getting is [2, 2, 2]. I can correct this behaviour by passing an empty dict everytime like foo(i, obj={}) but my question why by default, the foo function not initialzing the obj with {}?

sagar
  • 725
  • 2
  • 13
  • 30
  • 4
    No, a dictionary is mutable and the basic rule is **never use a default value for a mutable argument**. https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – NotAName Jun 10 '21 at 05:47
  • 2
    Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – KetZoomer Jun 10 '21 at 05:48
  • 1
    The answer in least astonishment thread tagged above is excellent. – Martin Jun 10 '21 at 05:52
  • It is clear. Thanks everyone. – sagar Jun 10 '21 at 05:57

0 Answers0