[Python-ideas] nonlocal functions

Masklinn masklinn at masklinn.net
Tue Oct 20 18:43:15 CEST 2009


On 20 Oct 2009, at 18:00 , MRAB wrote:
> Bruce Leban wrote:
> I'd prefer:
>
> def foo():
>    a = 1
>    b = 3
>    def bar():
>        nonlocal *
>        local b
>        a = 2
>        b = 4
>    return (a,b)
>
> if a later 'local' can override an earlier 'nonlocal', or:
>
> def foo():
>    a = 1
>    b = 3
>    def bar():
>        local b
>        nonlocal *
>        a = 2
>        b = 4
>    return (a,b)
>
> if a 'nonlocal' can act as a catch-all for any names not previously
> mentioned.

If you go that route, I'd suggest removing all the legacy stuff and  
just using "let" to create a new binding in the current scope:

def foo():
     let a = 1
     let b = 3
     def bar():
	a = 2
         let b = 4
     bar()
     return  (a, b) # returns (2, 3)

Plus it allows the compiler to statically catch typos:

def foo():
     let some_very_complex_type = 42
     def bar():
         some_very_complex_typo = "oh noes" # not a new binding, no  
existing binding for that name => warning(*)
     bar()
     return some_very_complex_type

You can even get "two in one" and use the keyword to create explicit  
scopes:

def foo():
     let foo="whatever", bar=42:
         do_something_with(foo, bar)
     return foo # warning, no foo in scope

which would probably be useful mostly for code clarity purposes.

*: warning, not error, because the programmer could be manipulating  
locals() directly, or something like that.



More information about the Python-ideas mailing list