[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Jan Kaliszewski zuo at chopin.edu.pl
Thu Sep 29 00:36:14 CEST 2011


Guido van Rossum dixit (2011-09-28, 08:38):

> @init(n=1, lock=Lock())
> def global_counter():
>   nonlocal n, lock
>   with lock:
>     print(n)
>     n += 1
> 
> Alas, the problem is that you can't actually implement such a
> decorator, not even using an extension module, because the compiler,
> upon seeing the "nonlocal n, lock", ignoring the decorator (since it
> should be applied at run time, not at compile time), will complain
> that there isn't actually an intermediary outer scope defining either
> n or lock.
> 
> Some ways out of this:
> 
> - let the compiler special-case a certain built-in decorator name at
> compile-time (unorthodox, not impossible)
> 
> - different syntax, e.g.
>   @[n=1, lock=Lock()]
> or
>   @in(n=1, lock=Lock())
> or even
>   in n=1, lock=Lock()
> 
> (all followed by "def global_counter() etc.")
> 
> Of course once there's different syntax, the nonlocal declaration in
> the function is redundant. And clearly I'm back-peddling. :-)

And what about:

    @nonlocal n=1, lock=Lock()
    def global_counter():
        "we don't need to repeat nonlocal in the body"

or
    
    @nonlocal(n=1, lock=Lock())
    def global_counter():
        "we don't need to repeat nonlocal in the body"

?

Cheers.
*j




More information about the Python-ideas mailing list