Pointers to variables

Randall Hopper aa8vb at vislab.epa.gov
Fri Apr 23 08:07:21 EDT 1999


     Thanks for the replies and suggestions to use setattr to set variables
by name.

     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.

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.  

     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:

    (1)  min = [ 0 ]
         max = [ 0 ]

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

    (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

but this one doesn't:

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

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.

Does this sound about right?

Randall




More information about the Python-list mailing list