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}
|