Is 'everything' a refrence or isn't it?

Claudio Grondi claudio.grondi at freenet.de
Wed Jan 4 23:51:06 CET 2006


Steven D'Aprano wrote:
> On Wed, 04 Jan 2006 10:54:17 -0800, KraftDiner wrote:
> 
> 
>>I was under the assumption that everything in python was a refrence...
>>
>>so if I code this:
>>lst = [1,2,3]
>>for i in lst:
>>   if i==2:
>>      i = 4
>>print lst
>>
>>I though the contents of lst would be modified.. (After reading that
>>'everything' is a refrence.)
> 
> 
> See, this confusion is precisely why I get the urge to slap people who
> describe Python as "call by reference". It isn't.
> 
> It isn't "call by value" either -- Python never copies objects unless you
> explicitly tell it to.
> 
> It is "call by object" -- you pass around *objects*. Internally, this is
> quite fast, because the entire object doesn't need to be moved, only
> pointers to objects, but you don't get the behaviour of either call by
> reference or call by value.
> 
> In the above code, i is a name bound one at a time to the ints [1,2,3].
> When you re-assign i to 4, that doesn't change the object 2 into the
> object 4, because ints are immutable. Only the name i is rebound to a new
> object 4. That doesn't change objects like lst which include 2 inside them. 
> 
> See this for more detail:
> 
> http://effbot.org/zone/call-by-object.htm
> 
> 
It seems to be hard to explain it all in a straighforward way without 
using pictures showing what happens when an assignment is processed 
demonstrating what is what and how it is called. Probably a small nice 
movie could be here the right medium to be handed over to Python newbies 
coming from C to give some hints towards proper understanding. Replacing 
one word with another is not sufficient to avoid confusion as the 
concept is probably not always easy to grasp (I have still problems to 
get the idea how it works 'inside' with this local and global 
dictionaries and so on).
Lack of knowledge about a good reference was the reason why I decided to 
give a reply here inspite of the fact, that so many other postings were 
already there, but none (including mine) which covered all aspects, so 
that I could say: "Wow! It is an excelent explanation and there is 
nothing which must be added to it!".
Is there anywhere an ultimative enlightening explanation of the concept 
of identifiers and variables in Python for use in case the next posting 
of that kind hits comp.lang.python and it sure will as they are coming 
in quite regular.
http://effbot.org/zone/call-by-object.htm is sure an attempt of a good 
explanation, but in my eyes still nothing what immediately enlightens.

Claudio



More information about the Python-list mailing list