[Python-ideas] A real life example of "given"

Chris Angelico rosuav at gmail.com
Thu May 31 08:55:46 EDT 2018

On Thu, May 31, 2018 at 10:24 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Do you have an equally compelling example for your given-comprehension
> syntax? I didn't think your example was obviously better than what we
> can already do:
>     # calculate tx only once per x loop
>     [process(tx, y) for x in xs given tx = transform(x) for y in ys]
>     # existing solution
>     [process(tx, y) for tx in (transform(x) for x in xs) for y in yz]

# alternate existing solution
[process(tx, y) for x in xs for tx in [transform(x)] for y in yz]

This syntax allows you to use both x and tx in the resultant
expression. For instance:

[process(value, row_total) for row in dataset for row_total in
[sum(row)] for value in row]

ret = []
for row in dataset:
    row_total = sum(row)
    for value in row:
        ret.append(process(value, row_total))

If done without optimization, each row would take O(n²) time, but this
way it's O(n).

I think Serhiy was trying to establish this form as a standard idiom,
with optimization in the interpreter to avoid constructing a list and
iterating over it (so it would be functionally identical to actual
assignment). I'd rather see that happen than the creation of a messy
'given' syntax.


More information about the Python-ideas mailing list