Python-list digest, Vol 1 #10442 - 15 msgs

Patrick Miller patmiller at llnl.gov
Thu Apr 11 13:33:24 EDT 2002


Denis writes:
> But this work and AFAIK is not implementation dependent:
> 
> >>> def set(name, val):
> ...     exec '%s=__val__' % name in {'__val__': val}, \
> ...                           sys._getframe().f_back.f_locals
> ...
> >>> a = 7
> >>> set('a', 99)
> >>> a
> 99

Alas, it doesn't really work for the reasons outlined regarding changing
local variables in one of my previous messages.  In your test
case, you have the illusion of it working because the
outermost frame's local and global dictionaries are coincident
(i.e. a is treated as a member of the global variable namespace).
The example below shows that if you enter a new frame, then
locals() does NOT allow you to update values.

Another victim of the locals() globals() namespace wars...
Pat


% python
Python 2.1 (#1, Aug 23 2001, 10:42:50) [C] on osf1V4
Type "copyright", "credits" or "license" for more information.
>>> def set(name,val):
...   import sys
...   exec '%s=__val__' % name in {'__val__': val}, sys._getframe().f_back.f_locals
...
>>> a = 7
>>> set('a',99)
>>> print a
99
>>> # So far so good, but......
...
>>> def test():
...   b = 7
...   set('b',99)
...   print b
...
>>> test()
7
>>>

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

Access to power must be confined to those who are not in love with it. 
 -- Plato





More information about the Python-list mailing list