3 ms·
How come they are using a new := operator instead of using equals?
by ihuman 7y ago
How come they are using a new := operator instead of using equals?
- dragonwriter 7y agoWhich equals? = (existing) is statement assignment == (existing) is expression equality := (new) is expression assignment
- ihuman 7y agoJust 1 equals. It could assign a statement to a variable, and return that value/variable to the if statement to check for truthyness 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"); }
- dragonwriter 7y agoThat works if “if” statements were the only place the assignment expression operator could be used. 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)
- magicalhippo 7y agoIt works in C, and have caused countless bugs in C (and C++). 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.
- andolanra 7y agoThey address this briefly in the PEP[0], and it's largely because they want to be very clear about when it's happening. The distance between 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-existing-assignment-into-an-expression https://www.python.org/dev/peps/pep-0572/#why-not-just-turn-...
- jimktrains2 7y agoThat's literally the point: it's not the assignment operator. 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.