From: fredrik at pythonware.com (Fredrik Lundh)
Date: Fri, 23 Apr 1999 12:37:27 GMT
Subject: Pointers to variables
References: <19990422121403.A279051@vislab.epa.gov> <wkk8v4ef5e.fsf@turangalila.harmonixmusic.com> <19990423080721.A344578@vislab.epa.gov>
Message-ID: <021801be8d86$0d3ba7a0$f29b12c2@pythonware.com>
Content-Length: 2164
X-UID: 264                                                  

Randall Hopper wrote:
>      I think I understand the source of my confusion.  This construct:
> 
>      for ( var, val ) in [( min,   1 ), ( max, 100 )]:
> 
> isn't pairwise assignment to all the values of the list.  If it were, val
> would be an alias for the variable min, then an alias for max, etc.

but that's exactly what it is.  read on!

> This actually builds a completely new list:
> 
>      [( valueof(min), 1 ), ( valueof(max), 100 )]
> 
> in memory first, which is then iterated over.  This is why my original
> example didn't work.  

nope.  that's not the reason.  read on!

>      Also, the "valueof()" relation for some types in python (apparently)
> is a reference rather than a value (lists, objects, etc.) which explains
> why these examples work:

*EVERYTHING* is a reference.  a pointer.  a memory address.
or whatever term you prefer.

>     (1)  min = [ 0 ]
>          max = [ 0 ]
> 
>          for ( var, val ) in [( min,   1 ), ( max, 100 )]:
>            var[0] = val

here, you modify the object in place (through the reference),
by assigning to a list slot.

corresponding C-ish code:

    varPtr->setitem(0, valPtr);

>     (2)  class Val:
>            def __init__( self, num ):
>              self.num = num
> 
>          min = Val(0)
>          max = Val(0)
> 
>          for ( var, val ) in [( min,   1 ), ( max, 100 )]:
>            var.num = val

here, you modify the "var" object in place by
setting an attribute.

corresponding C-ish code:

    varPtr->setmember("num", valPtr);

> but this one doesn't:
> 
>     (3)  min = 0
>          max = 0
>          for ( var, val ) in [( min,   1 ), ( max, 100 )]:
>            var = val

here, you tell python to change the binding for the name "var"
in the local name space so it points to the same thing as the
name "val".

corresponding C-ish code:

    varPtr = valPtr;

or rather:

    setlocalname("var", valPtr);

> So basically this is just a little asymmetry in the language.  Putting a
> variable in a list/tuple (valueof(var)) performs a shallow copy rather than
> a deep copy.

nope.  content is never copied.  only references.  all the time.
perfect symmetry.

</F>





