Please explain this strange Python behaviour
jjposner at snet.net
Thu Apr 30 17:40:39 CEST 2009
Stephen Hansen wrote:
> 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... :)
Believe me, I don't want that to happen!
> 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.
This is the kind of explanation I was looking for in the "why are
default values shared" writeup.
> 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?
The interpreter *could* take the extra trouble to do that with default
arguments, because many users seems to expect that behavior. But I now
understand how the decision *not* to treat default arguments as special
cases produces the actual behavior. Many thanks, Stephen.
More information about the Python-list