Default value for optional parameters unexpected behaviour?

Corey Richardson kb1pkl at aim.com
Sun Jun 26 14:36:12 EDT 2011


Excerpts from Marc Aymerich's message of Sun Jun 26 14:28:30 -0400 2011:
> Hi,
> I'm trying to define a function that has an optional parameter which
> should be an empty list whenever it isn't given. However, it takes as
> value the same value as the last time the function was executed. What
> is the reason of this behaviour? How does python deal with default
> values (i.e. when are they assigned/created)?
> 
> Thanks :)
> 

Really common mistake, I made it myself too. When Python evaluates the 
function, it sees the default parameter of `foo' as the new object you
create with []. It keeps that object around. The proper idiom instead of

> >>> def a(foo=[]):
> ...  foo.append(1)
> ...  print foo
> ...

is

def a(foo=None):
	if foo is None:
		foo = []
	foo.append(1)
	print foo
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20110626/52f14619/attachment.sig>


More information about the Python-list mailing list