Why can't I use the walrus operator :=
to assign to an attribute? It works when assigning to a local variable:
my_eyes = ["left", "right"]
if saved_eye := my_eyes.index("left"):
print(saved_eye)
# outputs >>> 0
But it is a syntax error if I try to assign to an object attribute:
class MyEyes:
def __init__(self):
self.eyes = ["left", "right"]
self.saved_eye = None
def ohyes(self):
if self.saved_eye := self.eyes.index("left"):
print(self.saved_eye)
x = MyEyes()
x.ohyes()
# raises
# >>> if self.saved_eye := self.eyes.index("left"):
# >>> SyntaxError: cannot use assignment expressions with attribute
I mean I can bypass the error using a temporary local variable but why would this happen? I believe 100% it is a legal syntax.
The syntax is illegal, as stated in the
PEP 572
, where the walrus operator (aka "assignment expression") is defined:It's a little bit wordy, but this means that the walrus operator doesn't support assignment for attributes.
The error you are getting is quite specific to the situation too, validating this ("cannot use assignment expressions with attribute" means "cannot use walrus operator setting an attribute").