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
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