default value in __init__

David C. Ullrich dullrich at sprynet.com
Thu Oct 9 14:48:19 EDT 2008


In article 
<5f3a6fdc-40e5-4450-b65d-066f87f27309 at v53g2000hsa.googlegroups.com>,
 kenneth <kenneth at inwind.it> wrote:

> On Oct 9, 10:14 am, Christian Heimes <li... at cheimes.de> wrote:
> > kenneth wrote:
> > > the 'd' variable already contains the 'self.d' value of the first
> > > instance and not the default argument {}.
> >
> > > Am I doing some stupid error, or this is a problem ?
> >
> > No, it always contains the default argument because default values are
> > created just ONE 
> > TIME.http://effbot.org/pyfaq/why-are-default-values-shared-between-objects..
> > .
> 
> 
> Wow, it's a very "dangerous" behavior ...
> 
> Just to know, is this written somewhere in the python documentation or
> one has to discover it when his programs fails to work ;-) ?

At least once a week someone discovers this "problem", makes a
post about it here, and then someone points to the spot in the
documentation where it's explained.

Seems to me that people often site the "important warning" in
the tutorial. Of course there's no reason anyone would bother
going through the tutorial - just for fun I looked in the
official Python Reference Manual to see whether they're explicit
about this or require the reader to figure it out from something
else they say.

There's a section titled "7.6 Function definitions". About halfway
through that section there's a _bold face_ statement 
"Default parameter values are evaluated when the function definition is 
executed.", followed by an explanation of how that can lead to
the sort of problem above.

So I guess it _is_ awfully dangerous. They should really explain
this aspect of the language's behavior to people who don't read
the formal definition and also don't work through the tutorial.


> Paolo

-- 
David C. Ullrich



More information about the Python-list mailing list