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

Victor Stinner vstinner at redhat.com
Thu Jul 5 11:07:58 EDT 2018


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").

Victor


More information about the Python-Dev mailing list