Please explain this strange Python behaviour

Stephen Hansen apt.shansen at gmail.com
Thu Apr 30 10:22:54 EDT 2009


>
>
> * This writeup, and the virtually identical one at effbot.org that Diez
> referenced, address the *what* of default arguments, but don't really
> address the *why*, beyond the statement that "Default values are created
> exactly once, when the function is defined (by executing the *def* <
> http://effbot.org/pyref/def.htm> statement)". After all, if parameter
> values are supplied to a function when it is called, a newly minted set of
> default values could be supplied at that time, also. So *why* was Python
> designed one way instead of the other?
>

I have a feeling this might start one of those uber-massive "pass by value /
reference / name / object / AIEE" threads where everyone goes around in
massive circles explaining how Python uses one or another parameter passing
paradigm and why everyone else is wrong... but... :)

The thing is, parameter values are NOT supplied to a function when it is
called.

When you call a function, there's no creation or copying of any values of
any kind. The objects you pass in are passed in and the function receives
those exact same objects. Within the function a local name is made which
binds to an existing object that is specified when it is called-- or if a
default is provided, that. In all cases these objects already exist before
the call happens.

Despite the fact that using mutable objects as default arguments is a
frequent source of quirked-eyebrows and head-scratching for those new to
Python, to do anything else would be weirdly magical. You'd basically have
to go and call copy() on any default arguments specified in the function; at
which point why are you copying those and not the other arguments? It just
doesn't make sense with how Python handles name
binding consistently throughout the entire language. In this corner case
that just seems weird at first to people.

--Stephen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090430/c8c30e94/attachment-0001.html>


More information about the Python-list mailing list