locals(): snippets and a question

Eric Jacobs none at none
Mon Mar 27 15:14:03 EST 2000


In article <38DEF357.CA5BC5B7 at erols.com>,
"Edward C. Jones" <edcjones at erols.com> wrote:
: 
> # 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()

Not really, no. But if you don't mind a really nasty hack, you
can do:

import sys

class watch:
    def __init__(self, locals_frame):
        self.locals = lambda fr=locals_frame: fr.f_locals

def fun3():
    try:
        raise ""
    except:
        w = watch(sys.exc_info()[2].tb_frame)
    print w.locals()
    a = 7
    print w.locals()


.. minding your circular reference problems, of course.

The "magic" PyFrame_FastToLocals() call is hidden in the
getattr for f_locals in a frame object, in addition to
locals(). Unfortunately, using an exception is the only
easy way to recover frame objects from within Python itself.

The current implementation of locals() really makes no
sense, as you pointed out. Probably the correct way to
implement it would to have locals() return a dictionary-like
object that shadows the actual local variables in the frame.
Its copy() method would invoke the functionality of
PyFrame_FastToLocals(), creating a normal dictionary from
the current state. At least then, the copying could be
explicitly controlled.



More information about the Python-list mailing list