updating locals() and globals() (WAS: How do I do this? (eval() on the left hand side))
Bengt Richter
bokr at oz.net
Thu Dec 9 15:24:25 EST 2004
On Wed, 8 Dec 2004 20:22:52 -0500, "Terry Reedy" <tjreedy at udel.edu> wrote:
>To respond to and summarize several posts in this discussion:
>
>Within a function, where the local namespace is distinct from the global
>(module) namespace, CPython usually implements the local namespace
>internally as a fixed-length array. When this is true, locals() is a
>*copy* of the local namespace and not the namespace itself. Once that dict
>is created, the history of how it was created is immediately forgotten,
>just as with any other ordinary Python dict.
>
>That dict can be bound to a name or other target and modified like any
>other dict, and there could be reasons to do so. However, modifying it has
>no more effect on the local namespace than modifying any other local dict.
>
It doesn't appear to be _quite_ ordinary though (note that print d['x'] inside
does print 3 the first time and 5 after the d['x']=5 assignment, but is not
returned in d when d returns in the results):
I think I'd rather locals() totally refuse updates than allow retrievable updates
in a way that leaves me wondering what kind of object it is and what happens to it
when it is exported from a function (some kind of closure stuff involved in converting
a proxy to a dict? (will speculation)) ;-/
>>> def f():
... x = 3
... d = locals()
... D = dict(locals())
... print 'x', x
... print "d['x']",d['x']
... d['x'] = 5
... print 'x', x
... print "d['x']",d['x']
... print "D['x']", D['x']
... D['x'] = 7
... print "d['x']",d['x']
... print "D['x']", D['x']
... return d, D, locals()
...
>>> d,D,L = f()
x 3
d['x'] 3
x 3
d['x'] 5
D['x'] 3
d['x'] 5
D['x'] 7
>>> d
{'x': 3, 'd': {...}, 'D': {'x': 7, 'd': {...}}}
>>> D
{'x': 7, 'd': {'x': 3, 'd': {...}, 'D': {...}}}
>>> L
{'x': 3, 'd': {...}, 'D': {'x': 7, 'd': {...}}}
>>> L['d']['x'] # not 5
3
>>> L['D']['x'] # is 7
7
>>> d['x']
3
>>> D['x']
7
>>>
Regards,
Bengt Richter
More information about the Python-list
mailing list