[Tutor] beginner: using optional agument in __init__ breaks my code

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jun 26 16:46:41 CEST 2006


>> The values of optional arguments are only once evaluated (when Python 
>> reads the definition). If you place there mutable objects like e.g. a 
>> list most of the time the effect you see is not what you want. So you 
>> have to write it a bit different.
>>
>>      def __init__(self, q = None):
>>          if not q: q = []
>>          self.queue = q
>>
>> Now you get a fresh list for each instance.
>>
> Thank you very much. I will use your code as a "recipe", while I still 
> try to understand the mechanism and the reasons behind it. For me this 
> feels odd.


Hi Barbara,

It is odd.  *grin*

There were at least two possible design choices to Python's behavior here. 
On every __init__, should Python re-evaluate the default argument 
expression?  Or should that value be fixed?

The designers of Python chose to the former, which leads to slight 
weirdness like this.


More information about the Tutor mailing list