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

Jan Kaliszewski zuo at chopin.edu.pl
Sat Oct 1 13:44:28 CEST 2011


Jan Kaliszewski dixit (2011-09-30, 23:32):

> Nick Coghlan dixit (2011-09-30, 14:14):
> 
> > If a "function state decorator" approach is used, then yeah, I agree
> > it should come immediately before the main part of the function
> > header.
> 
> Yes, it seems to be a necessary requirement.
> 
> > However, I'm not seeing a lot to recommend that kind of syntax
> > over the post-arguments '[]' approach.
> 
> IMHO @(...) has two advantages over '[]' approach:
> 
> 1. It keeps all that 'additional scope'-stuff in a separate line, making
> the code probably more clear visualy, and not making the crowd of
> elements in the '...):' line even more dense (especially if we did use
> annotations, e.g.: '...) -> "my annotation":').
> 
> 2. It is more consistent with the existing syntax (not introducing
> '='-based syntax within []; [] are already used for two different
> things: list literals and item lookup -- both somehow leading your
> thoughts to sequence/container-related stuff).

And also -- what maybe is even more important --

3. Placing it before (and beyond) the whole def statement makes it
easier to *explain* the syntax:

    @(x=1, lock=Lock())
    def do_foo(y):
        nonlocal x
        with lock:
            x += y
        return x

as being equivalent to:

    def _closure_provider():
        x = 1
        lock = Lock()
        def do_foo(y):
            nonlocal x
            with lock:
                x += y
            return x
        return do_foo
    do_foo = _closure_provider()
    del _closure_provider

Cheers.
*j




More information about the Python-ideas mailing list