Using exec with local dictionary from another routine

Robert McLay mclay at cfdlab.ae.utexas.edu
Fri Aug 9 11:19:39 EDT 2002


I would like to set the value of a local variable in one routine (say
main()) and change
the same local variable in another routine.   Where does this come up
you ask?
Well I wish to use the stream decorator pattern to modify a stream then
later reset it.

The problem come down to how to change the value of a local variable
from a
different routine.  Below is a simple example that doesn't work:

#!/usr/bin/env python

def delay(ldict):
  exec "print 'In delay id(f):',id(f);"\
       "print f; f = 3; print f; print 'In delay id(f):',id(f)" in
ldict,ldict

def main():
  f = 2
  print "In main  id(f):",id(f)
  delay(locals())
  print id(f)
  print "f:",f

if (__name__ == "__main__"):
  main()

So when I run this I get:

In main  id(f): 135272696
In delay id(f): 135272696
2
3
In delay id(f): 135272636
135272696
f: 2

So when in the "delay" routine it knows the id(f) is the same as in the
main function
but when the change the value of "f" in the exec statement it creates a
new "f" and
assigns it to 3.  What am I missing here?




More information about the Python-list mailing list