Hacker News new | past | comments | ask | show | jobs | submit login

Which equals?

= (existing) is statement assignment

== (existing) is expression equality

:= (new) is expression assignment




Just 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");
  }


It 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.


That 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)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: