[New-bugs-announce] [issue30471] "as" keyword in comprehensions

Dávid Nemeskey report at bugs.python.org
Thu May 25 04:13:59 EDT 2017


New submission from Dávid Nemeskey:

Currently, the "as" keyword in supported in import and with statements to bind an object to a name. I think it would be nice to have the same functionality in list/dict/etc. comprehensions as well.

Rationale: as I understand, comprehensions are preferred over map/filter + lambdas for creating modified versions of sequences (etc.) in Python. They are indeed useful for replacing map, filter, or map(filter); however, filter(map) is currently not supported. This is not an unusual use-case, as the two examples below show. It is also evident that they are very wordy with lambdas, and could be much clearer with comprehensions:

    with open(file) as inf:
        lines = list(filter(lambda l: l, map(lambda line: line.strip(), inf)))
    items = dict(filter(lambda kv: kv[1] > 5,
                        map(lambda kv: kv[0], len(kv[1]), d.items())))

Currently the only way to do this with comprehensions are:

    with open(file) as inf:
        lines = [l for l in (line.strip() for line in inf) if l]
    items = {k: v for k, v in ((k, len(v)) for k, v in d.items()) if v > 5)}

, or

    items = {k: len(v) for k, v in d.items() if len(v) > 5}

The first option is as unwieldy and unreadable as the code with lambdas, while the second is ineffective as it calls len() twice (and of course here len() is just a placeholder for a potentially heavy operation).

I propose to allow the "as" keyword in comprehensions as well to bind the result of an operation in the output expression to a name that could be used in the optional predicate. In other words, provide a let-like functionality. Like so:

    with open(file) as inf:
        lines = [line.strip() as l for line in inf if l]
    items = {(k, len(v) as lenv) for k, v in d.items() if lenv > 5}

----------
messages: 294446
nosy: nemeskeyd
priority: normal
severity: normal
status: open
title: "as" keyword in comprehensions
type: enhancement

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30471>
_______________________________________


More information about the New-bugs-announce mailing list