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

Neil Girdhar mistersheik at gmail.com
Wed May 30 22:22:10 EDT 2018

```On Wed, May 30, 2018 at 8:10 PM Steven D'Aprano <steve at pearwood.info> wrote:

> On Thu, May 31, 2018 at 04:06:51AM +1000, Chris Angelico wrote:
> > On Thu, May 31, 2018 at 3:59 AM, Neil Girdhar <mistersheik at gmail.com>
> wrote:
> > > This example shows additional flexibility:
> > >
> > > z = {a: transformed_b
> > >      for b in bs
> > >      given transformed_b = transform(b)
> > >      for a in as_}
> > >
> > > There is no nice, equivalent := version as far as I can tell.
> >
> > True. However, it took me several readings to understand what you were
> > doing here.
>
> Possibly you shouldn't have tried reading at 4am.
>
> Either that or I shouldn't be reading before I've had a coffee :-)
>
> Have I missed something that you have seen? Even if the syntax were
> legal, that seems to be a pointless use of an assignment expression.
> Since the new name "transformed_b" is only used once, we can and should
> just use the transform(b) in place:
>
> z = {a: transform(b) for b in bs for a in as_}
>

Chris just explained it to you.  You're calling transform too often.

>
> If we need to use it twice, we can do this:
>
> # assume "@" stands in for something useful
> z = {a: (transformed_b := transform(b)) @ transformed_b
>      for b in bs for a in as_}
>
>
> I'm not seeing the advantage of given, or any extra flexibility here,
> unless the aim is to encourage people to make syntax errors :-)
>
>
The flexibility of "given" is in giving names to elements of expressions
and comprehensions to avoid recalculation.

> What have I missed?
>
> Like you say, := and given both work for expressions.  "given" could
theoretically also be used in comprehensions.

>
>
> --
> Steve
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
> --
>
> ---
> You received this message because you are subscribed to a topic in the
> Google Groups "python-ideas" group.
> To unsubscribe from this topic, visit