[Python-ideas] Tweaking closures and lexical scoping to include the function being defined
Ron Adam
ron3200 at gmail.com
Mon Sep 26 16:31:47 CEST 2011
On Mon, 2011-09-26 at 10:08 -0400, Nick Coghlan wrote:
> On Mon, Sep 26, 2011 at 9:54 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> > On Mon, Sep 26, 2011 at 8:26 AM, Alex Gaynor <alex.gaynor at gmail.com> wrote:
> >> 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.
> >
> > To my mind, a 4:1 reduction in boilerplate lines, moving the function
> > name out to the top level, making it clear that there's only one
> > function (the inner one) that is kept around, avoiding repetition of
> > the variable name and the function name all count as fairly
> > substantial wins on the 'sugary goodness' front :)
>
> Oops, forget to mention that the toy examples I've been using for the
> sake of brevity fail to convey one of the benefits of the syntax (i.e.
> the elimination of all trailing boilerplate following the function
> definition), since the body of the inner function is so short.
>
> To be fair, a more accurate comparison would be to a '@closure'
> decorator along the lines of something I posted in the previous
> thread:
>
> def closure(f):
> # Not clear if this is actually the right thing to do
> # It depends on how you decide to handle annotations
> # and whether decorators are applied to the inner or the
> # outer function
> return functools.wraps(f)(f())
>
> @closure
> def FUNC():
> """Real function is the inner one"""
> VAR = EXPR
> def _inner(real, params, here): # Hidden signature!
> nonlocal VAR # Still have to repeat VAR
> # Arbitrarily long complex code here
> return _inner # Still have this trailing boilerplate
>
Could this help in cleaning up the lru_cash decorator in functools?
That seems like it may be a good test case as it has both defaults and
wrappers in it.
Cheers,
Ron (Looking in Lib for things this will help with.)
More information about the Python-ideas
mailing list