Possible to reach back in stack and grab calling function's locals()?

Ryan Kelly ryan at rfk.id.au
Thu Jun 17 19:55:41 EDT 2010


On Thu, 2010-06-17 at 16:02 -0400, python at 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
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/python-list/attachments/20100618/96c17468/attachment-0001.sig>


More information about the Python-list mailing list