If you want X, you know where to find it (was Re: do...until wisdom needed...)

Alex Martelli aleaxit at yahoo.com
Thu Apr 19 03:57:41 EDT 2001


"Douglas Alan" <nessus at mit.edu> wrote in message
news:lcpue9sh4c.fsf at gaffa.mit.edu...
    [snip]
> procedures and strings.  (Is there a way in Python of finding local
> variables by name on the Python stack so that a procedure can get and
> set variables in the caller's environment?  If so, you could do it,
> but it would be pretty ugly.)

_Examining_ local variables of the caller is possible (albeit
arguably not pretty), but _rebinding_ them (or binding new
ones) isn't (it might accidentally work in some implementation,
but the language reserves the right for the optimizer to change
the implementation of a function's local variables in any way
whatsoever).  In Python 2.1, I believe the canonical way to
examine the caller's local namespace has become

    sys._getframe(1).f_locals

which is said to be a "readonly dictionary" with the
name->value correspondences.  _getframe, by the way, is
documented as "This function should be used for internal
and specialized purposes only".


Alex






More information about the Python-list mailing list