help explaining default function arg weirdness
Robert Brewer
fumanchu at amor.org
Sun Oct 10 23:52:13 EDT 2004
John M. Gabriele wrote:
> This is almost straight out of the Python tutorial,
> section 4.7.1
>
> ------------------------code ---------------------
> #!/usr/bin/python
>
> def func( append_this, default_list=[] ):
> default_list.append( append_this )
> return default_list
>
> print func( "foo" )
> print func( "bar" )
> print func( "baz" )
> ------------------------/code-----------------
>
> And running it gives me this:
>
> ['foo']
> ['foo', 'bar']
> ['foo', 'bar', 'baz']
>
> which looks wrong to me. The explanation in the tutorial
> says "The default value is evaluated only once. This makes a
> difference when the default is a mutable object such as a
> list, dictionary, or instances of most classes."
>
> I don't get it: isn't default_list a local to func()?
The name is. The value, however, is just another spot on the heap.
> Doesn't it get created/destroyed with each call to func()
> so we'd get a fresh empty one with each function call?
Nope.
> What's the rationale for having the function remember
> default_list across calls?
http://www.python.org/doc/faq/general.html#why-are-default-values-shared
-between-objects
The setting of default values is performed when the function is defined
(only once), not when it is called (each time).
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list