default argument in method
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Dec 15 18:56:31 EST 2010
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/
--
Steven
More information about the Python-list
mailing list