[wingide-users] bug or feature
sijben at eemvalley.com
Sun Aug 21 01:54:20 EDT 2005
Brian and Martijn,
thanks very much for this quick response. I indeed had not counted on
that underwater behaviour.
Martijn Pieters wrote:
> Paul Sijben wrote:
>> I am running into a problem which I believe to be a bug in python.
>> I am creating a set of objects, remove it and then create them anew.
>> The definition is:
>> class TicketsList(MListof):
>> def __init__(self,val=):
> Don't! See below.
>> Now when I call it with
>> I see the second time that I create this object it starts NOT EMPTY.
>> The val gets the SAME object list (checkes by the object references).
> That's because you use a mutable default value. The val= declaration
> creates that list with the method definition; NOT when you create
> instances! That means that if you alter val within __init__, the changes
> persist over the lifetime of your python program.
>> However when I leave the code unchanged but for the creation with
>> explicitly an empty list I am getting a nively empty list.
> Indeed, because you then create a new list for that instance.
> If you need a list (or dictionary or other mutable) for a default value,
> do not create that value as part of the default arguments for a method;
> the definition is only evaluated once on import.
> Instead, default these to None, and in the body of the method replace
> these with the actual default:
> class TicketsList(MListof):
> def __init__(self,val=None):
> if val is None:
> val = 
> Remember: method and function definitions are only evaluated once. Don't
> put mutables in them, ever. We al run into this once or twice as we
> learn python, and it's a feature, not a bug. :)
> The python FAQ:
> The python tutorial:
> The python reference manual:
> Many other places:
> Hope this helps,
> Martijn Pieters
More information about the wingide-users