On Thu, 2010-06-17 at 16:02 -0400, pyt...@bdurham.com 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.


  Cheers,

     Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

Attachment: signature.asc
Description: This is a digitally signed message part

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to