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

See:

The python FAQ:
http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects

The python tutorial:
http://docs.python.org/tut/node6.html#SECTION006710000000000000000

The python reference manual:
http://docs.python.org/ref/function.html

Many other places:
http://www.ferg.org/projects/python_gotchas.html#contents_item_6
http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html?page=2
http://mail.python.org/pipermail/python-list/2003-February/150530.html
http://www.nexedi.org/sections/education/python/tips_and_tricks/python_and_mutable_n/view
http://lists.gnu.org/archive/html/vampire-public/2004-01/msg00001.html
http://mail.python.org/pipermail/tutor/2005-February/035786.html
etc.

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