[Python-Dev] Using and binding relative names (was Re: PEP for Better Control of Nested Lexical Scopes)

Phillip J. Eby pje at telecommunity.com
Tue Feb 21 21:25:38 CET 2006


At 11:31 AM 2/21/2006 -0800, Josiah Carlson wrote:

>Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> >
> > It seems a bit inconsistent to say on the one hand
> > that direct assignment to a name in an outer scope
> > is not sufficiently useful to be worth supporting,
> > while at the same time providing a way to do it for
> > one particular scope, i.e. 'global'. Would you
> > advocate doing away with it?
>
>I didn't conceive of the idea or implementation of 'global', it was
>before my time.  I have found that *using* global can be convenient (and
>sometimes even directly manipulating globals() can be even more
>convenient).  However, I believe global was and is necessary for the
>same reasons for globals in any other language.

Here's a crazy idea, that AFAIK has not been suggested before and could 
work for both globals and closures: using  a leading dot, ala the new 
relative import feature.  e.g.:

    def incrementer(val):
        def inc():
            .val += 1
            return .val
        return inc

The '.' would mean "this name, but in the nearest outer scope that defines 
it".  Note that this could include the global scope, so the 'global' 
keyword could go away in 2.5.  And in Python 3.0, the '.' could become 
*required* for use in closures, so that it's not necessary for the reader 
to check a function's outer scope to see whether closure is taking 
place.  EIBTI.

Interestingly, the absence of a name before the dot seems to imply that the 
name is an attribute of the Unnameable.  :)  Or more prosaically, it treats 
lexical closures and module globals as special cases of objects.

You could perhaps even extend it so that '.' by itself means the same thing 
as vars(), but that's probably going too far, assuming that the idea wasn't 
too far gone to begin with.  I suspect functional folks will love the '.' 
idea, but also that folks who wanted to get rid of 'self' will probably 
scream bloody murder at the idea of using a leading dot to represent a 
scope intead of 'self'.  :)




More information about the Python-Dev mailing list