[Python-Dev] Explicit Lexical Scoping (pre-PEP?)

Evan Simpson evan at 4-am.com
Fri Jul 7 18:56:01 CEST 2006


Kevin Jacobs <jacobs at bioinformed.com> wrote:
> Why not extend the interface to the locals builtin and add a __getitem__
> that returns a proxy to access locals defined in other lexical scopes
> via __{get/set/del}attr_:
> 
> def counter(num):
>     num = 1
>     def inc():
>         locals[1].num += 1
>         return outer.num
>     return inc
> 
> Where, for CPython, locals[n] gives access to
> NamespaceProxy(sys._getframe(n).f_locals).

Two nits:  First, I suspect that you meant to write "return
locals[1].num".  Second, sys._getframe doesn't do what you want, here.
It reaches back up the call chain, not out into lexically containing scopes.

That said, I like the idea of giving "locals[]" the meaning you
intended.  It has the advantage of not adding any new keywords or
syntactic constructs, but the disadvantage of not explicitly signaling
that locals in a given scope will be twiddled elsewhere.  Also, for
efficiency's sake, it might be desirable to only allow a literal integer
as the index, and to deal with use of "locals[]" at compile time rather
than dynamically.  I'm not sure how much overhead would be involved in
enabling dynamic lookup of arbitrary lexically containing scopes, but I
would *not* want to enable stuff like "locals[i * 2 - 1]".

Cheers,

Evan @ 4-am



More information about the Python-Dev mailing list