defaults for function arguments bound only once(??)

Chris Rebert clp2 at rebertia.com
Sun Oct 4 02:37:06 EDT 2009


On Sat, Oct 3, 2009 at 11:29 PM, horos11 <horos11 at gmail.com> wrote:
> All,
>
> Another one, this time a bit shorter.
>
> It looks like defaults for arguments are only bound once, and every
> subsequent call reuses the first reference created. Hence the
> following will print '[10,2]' instead of the expected '[1,2]'.
>
> Now my question - exactly why is 'default_me()' only called once, on
> the construction of the first object?

Actually, the single call happens at the "definition-time" of the
function. As for why, it's less magical than re-evaulating it on every
function call when that parameter is not supplied a value; trust me,
the issue has been argued to death.

> And what's the best way to get
> around this if you want to have a default for an argument which so
> happens to be a reference or a new object?

See http://docs.python.org/tutorial/controlflow.html#default-argument-values
Essentially, use None as the default value, then check for it and
assign the real default value in the function body.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list