default argument in method

Hans-Peter Jansen hpj at urpla.net
Wed Dec 15 20:09:33 EST 2010


On Thursday 16 December 2010, 00:56:31 Steven D'Aprano wrote:
> On Wed, 15 Dec 2010 21:10:05 +0100, Hans-Peter Jansen wrote:
> > Since this is a major pitfall, it might be worth mentioning, that
> > mutable default arguments are generally a bad idea, as the default
> > arguments are evaluated just once, hence e.g. using an empty list
> > might contain the items, that were appended in earlier calls of
> > this method..
>
> It's only a pitfall for users who expect that default arguments are
> re- created every time you call the function; it's only a bad idea
> for code which relies on the default arguments being re-created each
> time.
>
> If you hold misunderstandings about the behaviour of a language,
> you'll have trouble understanding what code does. Default arguments
> are no different from any other feature.
>
> > Code, that _relies_ on such behavior should be yanked instantaneous
> > and the producer of such code should be punished with coding APL¹
> > on a dubeolsik hangul keyboard² for a year at least..
>
> Python code that relies on default arguments to *not* be re-created
> on each function call is no worse than (say) Ruby code that relies on
> default arguments *to* be re-created each time.
>
> I don't mean to be elitist (ah, who am I fooling, of course I do),
> but when coders of the skill and experience of the Effbot and Guido
> use mutable defaults, who are you to say they shouldn't?
>
> http://effbot.org/zone/default-values.htm
> http://www.python.org/doc/essays/graphs/

Hmm, thanks for the pointers, Steven. I stand corrected, as I won't 
argue with taste.. I like the part about the disastrous results 
specially. 

If such code would be used in any collaborations, I would expect an 
explicit comment at least.

Pete



More information about the Python-list mailing list