[wingide-users] bug or feature

Martijn Pieters mj at zopatista.com
Sat Aug 20 16:07:15 EDT 2005

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=[]):
> 		etc.

Don't! See below.

> Now when I call it with
> 	tickets=TicketsList()
> 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.
> 	tickets=TicketsList([])

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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 256 bytes
Desc: OpenPGP digital signature
Url : /pipermail/wingide-users/attachments/20050820/afcc6605/signature.bin

More information about the wingide-users mailing list