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

Ka-Ping Yee python-dev at zesty.ca
Thu Jul 6 07:02:19 CEST 2006


On Wed, 5 Jul 2006, Guido van Rossum wrote:

On 7/5/06, Phillip J. Eby <pje at telecommunity.com> wrote: > Using the classic nonsense example: > > def counter(num): > def inc(): > .num += 1 > return .num > return inc > Would this also use ..num to refer to num in an outer scope two levels removed?

I don't think there's any need for that. I see '.num' as just another way of saying "num, but don't make a new binding".

I agree with Guido that the best proposals so far are converging on the idea that it's more Pythonic to say "don't make a new binding" when a variable is used, than to declare "this is the scope for this binding" ahead of time.

Of those there are two kinds:

(a) State once (anywhere in a scope, but preferably at the
    beginning) that a variable is non-local.  This is like
    the "global" keyword works now, and this category includes:

      - Change the meaning of 'global'.
      - Add a new keyword 'outer' or 'nonlocal', etc.

(b) Indicate, when mentioning a variable, that the variable
    is non-local.  This category includes:

      - Say 'global.x' or 'outer.x' instead of 'x'.
      - Say '.x' instead of 'x'.

My favourite so far is to use a new keyword -- i think changing the meaning of 'global' would be misleading. '.x' is probably my next favourite, though i share Guido's concern about allowing both 'x' and '.x' to refer to the same thing.

I see that 'outer' is used as an identifier in hmac.py in the standard library and also as a variable in test_set*.py. On the other hand 'nonlocal' does not appear anywhere in the standard library. Thus, 'nonlocal' is the best option that i've seen so far; it's less likely to break anything and it says exactly what it means. I can't think of a more accurate keyword.

-- ?!ng



More information about the Python-Dev mailing list