locals(): snippets and a question

Edward C. Jones edcjones at erols.com
Mon Mar 27 00:36:23 EST 2000


#! /usr/bin/python
"""
The Python reference Manual, Section 4.1, Footnote 4.2 says:

     The current implementations [of globals() and locals()]
return the
     dictionary actually used to implement the namespace, except
for
     functions, where the optimizer may cause the local namespace
to be
     implemented differently, and locals() returns a read-only
dictionary.
"""
# When a is set to 7, the dictionary loc is not updated. I don't
think the
# documentation made any promises about this.
def fun1():
    loc = locals()
    a = 7
    print loc

fun1()

# If some operation is done that requires the dictionary returned
by
# locals(), loc is updated.
def fun2():
    loc = locals()
    a = 7
    locals()
#    eval('a')
#    exec('x = 0')
    print loc

fun2()

# Is there anything I can do to keep locals_dict updated from
within watch?
class watch:
    def __init__(self, locals_dict):
        self.locals_dict = locals_dict

def fun3():
    w = watch(locals())
    a = 7
    print w.locals_dict

fun3()





More information about the Python-list mailing list