Wouldn’t it be nice to have the walrus equivalents of +=
, -=
, *=
, /=
, @=
, etc? For example, this JavaScript code:
if (++a === 9) a = 0;
could translate to this in Python:
if (a :+= 1) == 9: a = 0
Wouldn’t it be nice to have the walrus equivalents of +=
, -=
, *=
, /=
, @=
, etc? For example, this JavaScript code:
if (++a === 9) a = 0;
could translate to this in Python:
if (a :+= 1) == 9: a = 0
if (a := a + 1) == 9:
a = 0
works and is not an issue.
I don’t think so, no
you can write an equivalent that doesn’t require prefix incrementing (And all of the what that can bring) by formulating it differently without new syntax.
a = 0 if a == 8 else a + 1
Or maybe a = (a+1) % 9
.
This might be of value here:
if (a := (a + 1)) == 9: a = 0
can be simplified to
if (a + 1) == 9: a = 0
then to
if a == 9 - 1: a = 0
and finally
if a == 8: a = 0
in this particular case.
The walrus operator is useful in many situations requiring a single-use variable, but in the example above, it is redundant since the variable a
already exists. If the variable a
does not exist, you cannot use +=
or other compound assignment operators.
If we were to propose compound assignment operators inside an expression, they would take the form +:=
. However, these operators would create unnecessarily complex expressions, as demonstrated in the example above.
If the condition is false, these are not equivalent.
They are not equivalent. The false path also needs adjustment.
a = 8
for i in range(18):
if (a := a + 1) == 9:
a = 0
print(a, end=' ')
else:
print(a, end=' ')
print()
a = 8
for i in range(18):
if a == 8:
a = 0
print(a, end=' ')
else:
a += 1
print(a, end=' ')
0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8
If the user’s intent was to increment a
in the current scope:
a = 8
for i in range(18):
a = 0 if a + 1 == 9 else a + 1
print(a, end=' ')
0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8
I would always choose:
a = 8
if a == 8:
a = 0
else:
a += 1
print(a, end=' ') # 0
This is a bad example, walrus isn’t needed here and not using it, is more readable:.
a += 1
if a == 9:
a = 0
It’s also a bad example, because of it being a bad code.
Putting it all together:.
if a < 8:
a += 1
else: #unlikely
a = 0
There’s no need to add new operators, we can just re-use the existing compound assignment operators like in C:
#include <stdio.h>
int main() {
int i = 0;
printf("<%d>", i += 1); // prints <1>
}
The reason we use (a := 0)
in Python instead of (a = 0)
like in C, is just to prevent writing this accidentally instead of (a == 0)
. The same problem doesn’t apply to the other operators.
That being said, we still need to decide whether this is actually worth it.