From: Ryan Kelly on
On Thu, 2010-06-17 at 16:02 -0400, python(a) wrote:
> Is there an elegant way to reach back in the stack and grab the
> calling function's copy of locals()?

You can do it using my favourite function, sys._getframe:

>>> import sys
>>> def outer():
.... a = 1
.... inner()
>>> def inner():
.... print sys._getframe(1).f_locals
>>> outer()
{'a': 1}

The dict so obtained is of course read-only. If you like I can show you
the black magic necessary to *write* to the local variables of the
calling function, but it ain't pretty :-)

> I'm working on a library that does lots of textmerge operations and am
> looking for a way to eliminate the need for many of the calls to our
> library to have to explictly pass locals() to our formatting
> functions.

I understand the desire, but that sounds like trouble to me. Explicit
is better than implicit and all that.

You might get away with it for purely internal code (heck, even the
standard library uses sys._getframe on occasion!) but I would hesitate
to have a public-facing API that snaffles locals from any function that
happens to call it.



Ryan Kelly | This message is digitally signed. Please visit
ryan(a) | for details

From: python on

Thank you very much - your example is exactly the technique I was
looking for.

My use case is unusual and we don't need to update the parent's version
of locals().

The code in question is an internal template library whose methods need
access to their caller's locals() so they can figure out how to expand
variable references in string expressions. Eventually this library will
be replaced with a more conventional template package; however, for the
moment, I'm just keeping what we currently have working smoothly :)