help explaining default function arg weirdness

J

John M. Gabriele

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top