I just learned that the new walrus operator (:=
) can't be used to set instance attributes, it's supposedly invalid syntax (raises a SyntaxError
).
Why is this? (And can you provide a link to official docs mentioning this?)
I looked through PEP 572, and couldn't find if/where this is documented.
Research
This answer mentions this limitation without an explanation or source:
you can't use the walrus operator on object attributes
Sample Code
class Foo:
def __init__(self):
self.foo: int = 0
def bar(self, value: int) -> None:
self.spam(self.foo := value) # Invalid syntax
def baz(self, value: int) -> None:
self.spam(temp := value)
self.foo = temp
def spam(self, value: int) -> None:
"""Do something with value."""
Trying to import Foo
results in a SyntaxError
:
self.spam(self.foo := value)
^
SyntaxError: cannot use assignment expressions with attribute