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

Tim Peters tim.peters at gmail.com
Fri May 11 14:44:41 EDT 2018

[Brendan Barnwell]
>> . . . and it's true the latter is a bit more verbose in that case for
>> little extra benefit.  But when the locally-defined value is used within
>> a more complicated expression (like the quadratic formula example), I
>> think readability goes down significantly.  To appease Tim, instead of
>> using the quadratic formula, though, I will use a more realistic example
>> that comes up fairly often for me: wanting to do some kind of
>> normalization on a piece of data for a comparison, while keeping the
>> unnormalized data for use within the block:
>>         if some_condition and (stuff:=
>> get_user_input()).lower().strip().replace('-', ''):
>> versus
>>         if some_condition and stuff.lower().strip().replace('-', '') given
>> stuff = get_user_input():

[also Brendan]
>         Ironically I weakened my argument by forgetting to finish my
> expression there.  I intended that chain of method calls to be used in a
> comparison to make the surrounding expression more complex.  So revise the
> above to
>         if some_condition and (stuff :=
> get_user_input()).lower().strip().replace('-', '') == existing_value:
> versus
>         if some_condition and stuff.lower().strip().replace('-', '') ==
> existing_value given stuff = get_user_input():

Even more ironically, to my eyes the original more strongly supported
your view than the rewrite ;-)

"given stuff =" stuck out in the original because it was preceded by
punctuation (a right parenthesis).

I had to read the rewrite 3 times before i realized you were even
_using_ "given", because there it's buried between two other names -
"existing_value given stuff" -  and visually looks more like it's
actually the 3rd of 4 words (because of the underscore in

Of course that would have been obvious in a Python-aware editor that
colored "given" differently, but as-is I found the original easy to
read but the rewrite a puzzle to decode.

Similarly, in the rewritten assignment expression spelling, it's
obvious at a glance that the test is of the form

    some_condition and  some_messy_expression == existing_value

but in the rewritten "given" sample that's obscured because
"existing_value" not only doesn't end the statement, it's not even
followed by punctuation.  Of course coloring "given" differently would
remove that visual uncertainty too.  For a dumb display, I'd write it

   if some_condition and (
       stuff.lower().strip().replace('-', '') == existing_value) given
stuff = get_user_input():

instead (added parens so that "existing_value" and "given" are
separated by punctuation).

More information about the Python-ideas mailing list