[Python-ideas] Inline assignments using "given" clauses

Chris Angelico rosuav at gmail.com
Sat May 12 20:36:32 EDT 2018


On Sun, May 13, 2018 at 10:06 AM, Neil Girdhar <mistersheik at gmail.com> wrote:
>
>> Take your choice of which you want:
>>
>> (spam if (mylist := expr) else eggs) + mylist
>> ((mylist := expr) if condition else eggs) + mylist
>> (spam if condition else (mylist := expr)) + mylist
>>
>> Of course, in the last two cases, you're going to get a NameError when
>> you try to add mylist if the ternary operator took the wrong branch.
>> Unless you already defined mylist earlier.
>
>
> That's the problem I'm showing.  This is impossible:
>
> (spam if (mylist := expr) else eggs) + mylist
>
> but just fine with given:
>
> ((spam
>   if mylist
>   else eggs) + mylist)
>  given mylist = expr)

I don't understand. How is that impossible with the colon-equals form?
The 'if' expression is always going to be evaluated, followed by
exactly one of 'spam' and 'eggs'. So mylist will be properly assigned
before you get to adding it onto the end.

ChrisA


More information about the Python-ideas mailing list