[Python-ideas] Map-then-filter in comprehensions

Nick Coghlan ncoghlan at gmail.com
Thu Mar 10 22:51:22 EST 2016


On 11 March 2016 at 12:58, Franklin? Lee <leewangzhong+python at gmail.com> wrote:
> On Thu, Mar 10, 2016 at 5:20 PM, Michał Żukowski <thektulu.pp at gmail.com> wrote:
>> 2016-03-10 17:53 GMT+01:00 Pavol Lisy <pavol.lisy at gmail.com>:
>>> We could discuss if "with expr as var" syntax is more beautiful. (or
>>> if it not against There should be one-- and preferably only one
>>> --obvious way to do it.)
>>>
>>> But why omit context manager semantics in "with expr as var" assignment
>>> syntax?
>>>
>>> I personally don't like idea that semantics could be context sensitive
>>> in this way. (and we could already do pretty complex things in
>>> comprehension)
>>                      I was thinking to reuse "with [expr] as [var]" but I
>> also don't like idea of context sensitive semantics, and I even thought that
>> maybe someone, someday would want to write "content = fp.read() with
>> open('foo.txt') as fp"...
>
> This is my understanding of `with Expr() as Name: Block()`, in
> pseudocode (ignoring exception handling).
>
>     _context = Expr()
>     Name = _context.__enter__(...)
>     exec(Block, {"Name": Name})
>     _context.__exit__(...)

with doesn't create a new scope - it's more akin to a try/finally
statement with a particular form (PEP 343 defines the full expansion,
and that expansion is still broadly accurate, although some the
specific details are different these days)

The only compound statements in Python that create new scopes are
"def" and "class".

It's also worth reading PEP 343 for Guido's explanation for why the
context management assignment syntax isn't "with VAR = EXPR": it's
because EXPR *isn't* the thing being assigned, but rather a stepping
stone towards obtaining that thing. This characteristic is true of all
of the places where "as" is currently used instead of "=":

    with CM_EXPR as VAR:
        # VAR = CM_EXPR.__enter__(), not CM_EXPR

    except EXC_TYPE_EXPR as VAR:
        # VAR = the caught exception, not the exception type constraint
        # There's an implied "del VAR" at the end of the suite, but
still not a full implicit scope

    import MODULE_REFERENCE as VAR
    from MODULE_REFERENCE import NAME as VAR
        # Here, the LHS isn't even a normal expression - it's a module
name, or a module name plus an attribute name

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list