[Python-Dev] PEP 572: intended scope of assignment expression

MRAB python at mrabarnett.plus.com
Thu Jul 5 11:39:15 EDT 2018


On 2018-07-05 16:07, Victor Stinner wrote:
> 2018-07-05 15:14 GMT+02:00 Gustavo Carneiro <gjcarneiro at gmail.com>:
>> I don't know if you're trying to propose something clever here, like "if (x
>> := func()):" would assign to 'x' only inside the "then" body of the if, but
>> IMHO that would be a terrible idea:
> 
> I don't propose to change the PEP 572. I'm trying to explain to myself
> where "if (var := expr): ..." would add anything to readers compared
> to "var = expr; if var: ...". I know that var is still valid after the
> if.
> 
> I'm not asking to raise a syntax error or even emit a linter warning
> if var is used after the if. I'm just thinking loudly where the PEP
> 572 is appropriate.
> 
> IMHO the following code should not use assignement expression.
> 
> Good:
> 
>          help = self._root_section.format_help()
>          if help:
>              help = self._long_break_matcher.sub('\n\n', help)
>              help = help.strip('\n') + '\n'
>          return help
> 
> Bad?
> 
>          if (help := self._root_section.format_help()):
>              help = self._long_break_matcher.sub('\n\n', help)
>              help = help.strip('\n') + '\n'
>          return help
> 
> IHMO using "help :=" here would send the wrong signal to the reader:
> as if help is not going to be used after the if, whereas it's the case
> ("return help").
> 
I think it's OK if it's:

     Do something, and if that succeeded, act on it.

but not if it's:

     Do something, but if that failed, do something else.


More information about the Python-Dev mailing list