Confusion: assignments create object references.

Mike C. Fletcher mcfletch at rogers.com
Fri Apr 11 13:16:18 EDT 2003


Havens, Peter wrote:

>// -----Original Message-----
>  
>
...

>//   The above never happened, I assure you. >:)    Python 
>// doesn't work this way.
>
>I'm a silly rabbit. I hand copied the test incorrectly. The real test was:
>
>  
>
>>>>L = 1
>>>>M = L
>>>>L
>>>>        
>>>>
>1
>  
>
>>>>M = 0
>>>>L
>>>>        
>>>>
>1
>  
>
>
>Those are the real results (I double checked), but now I'm really confused. Why does the former test (the one I lied about) above give expected results, and the later doesn't?
>
>  
>
Because Python isn't C ;) .  Seriously, what you want to think about is 
namespaces and names.  A name is a simple mapping from a string to a 
(smart (i.e. reference-counted)) PyObject * (under the covers).  That 
is, a name holds a reference (pointer) to an object.  That's all it ever 
holds a reference to.  It never holds a reference to another name  
"slot"(though it can hold the same string value as a name, but that's 
still just a string object).

When you do:

    M = L

what's happening is that the name M in the current namespace is given a 
pointer to the object currently pointed to by L, so if L is pointing to 
a list, M now points to that list.  M knows nothing about the name L, it 
has *its own* pointer to the list, and there's no dependence on L at 
all.  Complementarily, L knows nothing about M, so assigning a new 
object to L won't affect M either.

Your sequence of actions:

    L = 1 # L now points to the integer object 1
    M = L # M now points to the integer object 1
    M = 0 # M now points to the integer object 0

never changed the object to which L pointed, so L still points to the 
original object.

HTH,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list