[Tutor] Default list arguments in __init__
Kent Johnson
kent37 at tds.net
Sun Feb 22 04:02:15 CET 2009
On Sat, Feb 21, 2009 at 2:55 PM, spir <denis.spir at free.fr> wrote:
> Le Sat, 21 Feb 2009 11:38:49 -0800,
> Moos Heintzen <iwasroot at gmail.com> s'exprima ainsi:
>
>> Hi,
>>
>> This behavior was totally unexpected. I only caught it because it was
>> the only thing I changed.
Yes, it is a common trap and a FAQ:
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm
>> I guess I have to do it like this. It seems to work. (i.e. every foo
>> instance with default lst now has a unique new list.)
>>
>> def__init__(self, lst=None):
>> self.items = lst or []
>
> This is the right remedy. Except that I would write
> self.items = [] if lst is None else lst
> to avoid "tricking" with bools (personal taste).
These two versions have different behaviour if an empty list is passed
in. Most likely the second one will be what was intended.
Kent
More information about the Tutor
mailing list