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

Chris Angelico rosuav at gmail.com
Wed May 30 20:05:33 EDT 2018


On Thu, May 31, 2018 at 9:53 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> There is no nice, equivalent := version as far as I can tell.
>
> Given (pun intended) the fact that you only use transformed_b in a
> single place, I don't think it is necessary to use := at all.
>
> z = {a: transform(b) for b in bs for a in as_}
>
> But if you really insist:
>
> # Pointless use of :=
> z = {a: (transformed_b := transform(b)) for b in bs for a in as_}
>

That's the subtlety of the 'given' usage here. You fell for the same
trap I did: thinking "it's only used once". Actually, what he has is
equivalent to:

z = {a: tb for b in bs for tb in [transform(b)] for a in as_}

which means it evaluates transform(b) once regardless of the length of
as_. But it's really REALLY not obvious. That's why I actually prefer
the "interpolated 'for' loop" notation, despite it being distinctly
distasteful in general. At least it's obvious that something weird is
happening, so you don't instantly assume that you can inline the
single usage.

ChrisA


More information about the Python-ideas mailing list