Please explain this strange Python behaviour

Tim Chase python.list at tim.thechases.com
Thu Apr 30 07:46:55 EDT 2009


Train Bwister wrote:
> Please explain: http://python.pastebin.com/m401cf94d
> 
> IMHO this behaviour is anything but the usual straight forward and
> obvious way of Python.
> 
> Can you please point out the benefits of this behaviour?

http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions

Note the section marked "Important warning" in bold.  That single 
dict-as-default-argument is evaluated once when the function is 
defined, and shared between function-objects (the things created 
by "def" statements).

The way to do it is:

   def my_method(self, your_param, d=None):
     if d is None:
       d = {}
     do_stuff(d)

There _are_ cases where it's a useful behavior, but they're rare, 
so I don't advocate getting rid of it.  But it is enough of a 
beginner gotcha that it really should be in the Python FAQ at 
www.python.org/doc/faq/general/

-tkc






More information about the Python-list mailing list