binding a reference to a variable

Patrick Miller patmiller at llnl.gov
Thu Apr 11 11:56:32 EDT 2002


Bengt writes>
> >>> def set(name, val, ns=locals()):
>  ...     ns[name]=val
>  ...     return val

Bengt noted that 'ns' is local to the declaration module of the
'def set.'  

The workaround for that is

def set(name,val):
   import sys
   ns = sys._getframe().f_back.f_locals # local dictionary of caller
   ...

BUT WARNING!!!!! There is a bigger problem --  Changes to the local
dictionary are NOT reflected in the state of the execution.

The following does not work as intended....

def f():
   a = 7
   L = locals()
   print L.keys() # Prints ['a','L'] or some such
   L['a'] = 99  # Update the value in L
   print a      # But wait!  This prints out '7'

The issue is the implementation of the code object supporting f.
The value of the locals dictionary is created on the fly by
the call to locals().  The actual values of the local variables
are on a tiny, predefined stack frame that is used by the bytecode
interpreter wherein local variables are known only by an
integer offset.

Creating true "local" variables is astonishly tricky.

You can actually figure out where names map into the frame instance
(weave does (or will do) it), but it is messy and very implementation
dependent.

Pat

-- 
Patrick Miller | (925) 423-0309 | patmiller at llnl.gov

All the world's a stage, / And the men and women merely players: / They
have their exits and their entrances; / And one man in his time plays
many parts.  -- William Shakespeare





More information about the Python-list mailing list