help explaining default function arg weirdness

John M. Gabriele john3gz at bestwebz.net
Sun Oct 10 23:09:05 EDT 2004


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()?
Doesn't it get created/destroyed with each call to func()
so we'd get a fresh empty one with each function call?

What's the rationale for having the function remember
default_list across calls?

Thanks,
---J

-- 
--- remove zees if contacting via email ---



More information about the Python-list mailing list