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

Kevin Jacobs <jacobs@bioinformed.com> bioinformed at gmail.com
Fri Jul 7 03:56:06 CEST 2006


On 7/6/06, Evan Simpson <evan at 4-am.com> wrote:
>
> Talin wrote:
> > I propose to create a new type of scoping rule, which I will call
> > "explicit" lexical scoping, that will co-exist with the current
> > "implicit" scoping rule that exists in Python today.
>
> I'd like to toss one more variant into the mix.  If we really need to
> address variables in an intermediate scope, the most explicit way that I
> can think of doing so is to write (using Philip's example):
>
> def counter(num):
>     scope as outer # "outer" is an arbitrary identifier
>     def inc():
>         outer.num += 1
>         return outer.num
>     return inc
>



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).  In addition to having a
relatively pleasing and explicit syntax, this may be a feasible method for
allowing portable introspection into outer scopes without having to export
the whole frame object a la sys._getframe(n).  I strongly suspect that
Jython, IronPython, and PyPy would have little difficulty supporting (and
optimizing) this construct.

Lacking core language support, it is easy to roll an object that does just
what I suggest.  Actual implementation is left to a more motivated reader,
of course.

Just another crazy idea to throw into the pot.

-Kevin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20060706/3e422aae/attachment.html 


More information about the Python-Dev mailing list