why cannot assign to function call
timr at probo.com
Sun Mar 1 03:41:10 CET 2009
Ethan Furman <ethan at stoneleaf.us> wrote:
>Specifically, how is a new name (pbr) different, in Python, from a new
>name initialized as if by assignment (pbv)? It seems to me than you end
>up with the same thing in either case (in Python, at least), making the
> foo = ['Ethan','Furman']
> func(foo) # bar = foo
The problem here, in my view, is the terminology. It is true that, inside
the function "func", "bar" will refer to the same list that "foo" refers
to. However, it is inaccurate to think of this list as "foo". There
exists a list -- an anonymous list in object space -- and while "func" is
executing, there are two names bound to that list. So, the "bar.pop()"
instruction changes that anonymous list, you'll see those changes if you
inspect "foo" after the call.
> foo = ['Python','Rocks!']
> func(foo) # bar is new name for foo
> # is this any different from above?
Yes, it's different. If Python really had "pass by value", that function
call would pass a COPY of the list. The function would receive the list's
"value", not the list itself.
>If I have this right, in both cases foo will be reduced to a single-item
>list after func. Any further explanation you care to provide will be
Nope. Under pass-by-value semantics, "func" could dance on the list to its
heart's content, and "foo" would not be changed.
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list