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.
self.rest
isn't a variable, but rather an attribute of theself
object. See #64055814 for a bit more discussion. – Aleris