if x = y:
and if x == y:
is very small, and easy to ignore, so insisting on if x := y:
makes it very clear that what's happening won't be mistaken for comparison at a quick glance.[0]: https://www.python.org/dev/peps/pep-0572/#why-not-just-turn-...
The difference between = and == in an if causes many hugs in other languages. Using := for assignment in an expression instead of == means that you can't simply have a typo and have a bug.
= (existing) is statement assignment
== (existing) is expression equality
:= (new) is expression assignment
a=42
if b = a:
print(b)
else:
print("no")
Would print "42". It works in C int a,b;
a=42;
if(b=a){
printf("%d\n",b);
} else {
printf("no\n");
}It works less well if they can be used everywhere an expression can occur, including the right side of assignments—especially since Python has both multiple (x = y, z) and chained (x = y = z) assignment, which can be used together.
What does this mean if = is used for both assignment statements and assignment expressions:
x = y, z = 10, 20
When they are distinct, these have different meaning: x = y, z = 10, 20 # x: (10, 20), y: 10, z: 20
x = y, z := 10, 20 # x: (<existing value of y>, (10, 20)), y: <unchanged>, z: (10, 20)So much so that many have adopted the rule that the variable goes on the right, "if 42 = b", to make sure the compiler barfs when you intended to write "if b == 42".
With := it's less likely that mistake is made. I also find it visually more distinct, so easier to parse, but that might be very subjective.