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

Masklinn masklinn at masklinn.net
Mon Sep 26 15:03:49 CEST 2011


On 2011-09-26, at 14:26 , Alex Gaynor wrote:
> Nick Coghlan <ncoghlan at ...> writes:
>>    i = 88
>> 
>>    def f():
>>        nonlocal i from 17
>>        print(i)
>>        i += 1
>> 
>>  def outer():
>>    i = 17
>>    def f():
>>        nonlocal i
>>        print(i)
>>        i += 1
>>    return f
>> 
>>>>> f = outer()
> 
> You had me, you really did.  Right up until you showed the current equivalent.  
> This strikes me as a few things.
> 
> Most importantly, as you noted yourself, a pretty rare case, even in C static 
> variables are probably the rarest scope of variable.  This strikes me as a) not 
> saving very much code, it's like crappy HFS instead of real sugar ;), and b)
> not adding fundamental value, I think both blocks of code are equally readable.  
> Other examples of syntatic sugar, such as decorators, have code motion
> properties  that let you think about code in the places that makes sense, and I
> don't think this has that.
> 
An other thing which strikes me as weird is that the proposal is basically the
creation of private instance attribute on functions. Could you not get the same
by actually setting an attribute on the function (this can not be used in
lambdas in any case)?

    def f():
        print(f.i)
        f.i += 1
    f.i = 17

and some of the verbosity (but mostly reverse-reading) could be sucrosed-away
with a decorator:

    @setattribute(i=17)
    def f():
        print(f.i)
        f.i += 1

because as far as I can tell, if this can make it there is little justification for
keeping an explicit `self` (among other things).

This proposal also does not help with the "reverse argument hack" in lambdas, since
it's using a statement.


More information about the Python-ideas mailing list