Log in

No account? Create an account

Previous Entry | Next Entry

python arguments are post-its


>>> def foo(a): a = 2
>>> x = 1
>>> foo(x)
>>> x


>>> def bar(b): b.append(2)
>>> y = []
>>> bar(y)
>>> y

Alex Martelli dismisses newbie "by value or by reference" questions with the following:

The terminology problem may be due to the fact that, in python, the
value of a name is a reference to an object. So, you always pass the
value (no implicity copying), and that value is always a reference.

I find it simpler to explain as: the semantics of argument passing are
_exactly_ identical to that of assignment (binding) to a barename; you
can fruitfully see argument passing as local (bare) names of the called
function being assigned initial values by the caller (that's exactly
what happens, in practice). Now if you want to coin a name for that,
such as "by object reference", "by uncopied value", or whatever, be my
guest. Trying to reuse terminology that is more generally applied to
languages where "variables are boxes" to a language where "variables are
post-it tags" is, IMHO, more likely to confuse than to help.


( 2 comments — Leave a comment )
Apr. 3rd, 2007 10:44 pm (UTC)
I think I understand it on first glance. I hope so anyway. Maybe this will confirm it: so if you would have said y = [1], then called bar(y), y would still be equal to [2] after the call, right?
Apr. 3rd, 2007 11:04 pm (UTC)
After the call, y would be [1, 2]. Is that what you meant?

It's hard to put it more correctly than Alex did. It takes a minute to read it, but once it is grokked, enlightenment is achieved.

Anyway, I thought it was cool how once I dismissed my own "reference or copy" way of thinking, I actually got it.
( 2 comments — Leave a comment )