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

Steven D'Aprano steve at pearwood.info
Wed May 30 19:53:35 EDT 2018


On Wed, May 30, 2018 at 01:59:37PM -0400, Neil Girdhar wrote:

> This example shows additional flexibility:
> 
> z = {a: transformed_b
>      for b in bs
>      given transformed_b = transform(b)
>      for a in as_}

Is that even legal?

Again, you're putting half of the comprehension in the middle of 
the given expression. I believe that "given" expression syntax is:

    expression given name = another_expression

it's not a syntactic form that we can split across arbitrary chunks of 
code:

    # surely this won't be legal?
    def method(self, arg, x=spam):
        body
    given spam = expression


Comprehension syntax in this case is:

    {key:expr for b in it1 for a in it2}

(of course comprehensions can also include more loops and if clauses, 
but this example doesn't use those). So you've interleaved part of the 
given expression and part of the comprehension:

    {key: expression COMPRE- given name = another_expression -HENSION}


That's the second time you've done that. Neil, if my analysis is 
correct, I think you have done us a great service: showing that the 
"given" expression syntax really encourages people to generate syntax 
errors in their comprehensions.


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



-- 
Steve


More information about the Python-ideas mailing list