Say we have this assignment statement:
a = 5
Even though it'd obviously be ugly to do this for no reason, we could technically accomplish the same thing with:
(a := 5)
This still assigns 5 to a
, and the value that the walrus operator returns just isn't used.
Are there any cases where this replacement wouldn't work?
I think it should work anywhere.
So both normal and walrus assignment can be used as statements.
There's a special-case restriction that walrus assignments can't be used as top-level statements, which is why you have to put it in parentheses.
I thought there might be a possibility that it couldn't be used in th top-level code of a class, but this works:
class Foo:
(a := 1)
print(Foo.a) # prints 1