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

Jan Kaliszewski zuo at chopin.edu.pl
Fri Sep 30 18:45:35 CEST 2011


Ron Adam dixit (2011-09-30, 00:25):

> How about anonymous wrappers?
> 
>   @@(x=0)
>   def adder(y):
>       nonlocal x
>       x += y
>       return x
> 
> which would be the same as...
> 
>   def _(x=0):
>       def adder(y):
>           nonlocal x
>           x += y
>           return x
>       return adder
>   adder = _()

+1, though I'd rather prefer simply:

    @(x=0)
    def adder(y):
        nonlocal x
        x += y
        return x

And, of course, if you don't need to rebind the variable, `nonlocal`
would not be needed:

    @(lock=threading.RLock())
    def my_foo():
        with lock:
            "do foo"

IMHO it is better than @nonlocal because it uses already settled
@-decorator idiom and at the same time it does not pretend to be a
normal fuction-based decorator.

I like it. :) I think it would be not only clear and useful but also
beautiful.

Cheers.
*j




More information about the Python-ideas mailing list