[Tutor] PEP 572 -- Assignment Expressions

Steven D'Aprano steve at pearwood.info
Wed Nov 28 04:13:17 EST 2018


On Tue, Nov 27, 2018 at 08:26:04PM -0500, Avi Gross wrote:
> Ivo,

You've replied to the wrong mailing list. Ivo wrote to Python-List, not 
Tutor.

But now that you've raised the issue...


[Ivo asked]
>    Why:
>          if (match := pattern.search(data)) is not None:
>                # Do something with match
> 
>    What is wrong with:
>          if match = pattern.search(data) is not None:
>                # Do something with match
> 
>    Assignment expression or assignment statement, it's an assignment, right?
> It is very clear to everyone that it's an assignment! Can't it all just be a
> "="?

It seems that Ivo didn't read the PEP because that is discussed:

https://www.python.org/dev/peps/pep-0572/#id32

Despite Ivo's statement that it is "clear to everyone", the problem is 
that whenever you see an assignment x=y in an assignment, there's no 
obvious way of telling whether they meant assignment or it was a 
mistyped equality test x==y. So it is not clear at all.

In C, this confusion between = and == is a frequent source of serious 
bugs, including one attempt at inserting a back-door into the Linux 
kernel:

https://freedom-to-tinker.com/2013/10/09/the-linux-backdoor-attempt-of-2003/

https://lwn.net/Articles/57135/


Requiring the colon x:=y makes it less likely to mess up the assignment 
or comparison.



-- 
Steve


More information about the Tutor mailing list