On 4/23/19 8:57 AM, Arup Rakshit wrote:
> On 23/04/19 3:40 PM, Steven D'Aprano wrote:
>> Watch out here, you have a mutable default value, that probably doesn't
>> work the way you expect. The default value is created ONCE, and then
>> shared, so if you do this:
>> a = MyCustomList()  # Use the default list.
>> b = MyCustomList()  # Shares the same default list!
>> a.append(1)
>> print(b.list)
>> # prints [1]
>> You probably want:
>>       def __init__(self, list=None):
>>           if list is None:
>>               list = []
>>           self.list = list
> That is really a new thing to me. I didn't know. Why list=None in the
> parameter list is different than in the body of __init__ method? Can you
> elaborate this?

It arises because a function definition is an executable statement, run
right then.  So a default value in the parameter list is created right
then, and then used as needed, and if that default is a mutable (list,
dictionary, etc) you get surprises.  When an empty list is created in
the body, it happens each time the function object is called (it's a
method, but it's still just a function object). You can write some
experiments to show yourself this in action, it usually makes it sink in
more than someone telling you.

And don't worry, this is one of the most famous of all Python beginner
traps, we've all fallen in it.

Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:

Reply via email to