Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Python's walrus operator be used to set instance attributes?

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
like image 565
Intrastellar Explorer Avatar asked Sep 24 '20 22:09

Intrastellar Explorer


People also ask

What does the walrus operator do in Python?

The walrus operator creates an assignment expression. The operator allows us to assign a value to a variable inside a Python expression. It is a convenient operator which makes our code more compact. We can assign and print a variable in one go.

How does the walrus operator look in Python?

Assignment expression are written with a new notation (:=) . This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side. The assignment expression allows you to assign True to walrus , and immediately print the value.

How does the walrus operator look in Python group of answer choices name expression name expression name := expression name :: expression?

The operator := is called the walrus operator since it characterizes the look of the walrus. See the colon as eyes and the equal sign as its tusks. The walrus operator is used as an assignment expression. It allows you to assign a value to a variable while also returning the value.

Which version of Python has walrus?

The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8.


Video Answer


2 Answers

PEP 572 describes the purpose of this (emphasis mine):

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr.

self.foo isn't a variable, it's an attribute of an object.

The Syntax and semantics section specifies it further:

NAME is an identifier.

self.foo isn't an identifier, it's two identifiers separated by the . operator.

While we often use variables and attributes similarly, and sometimes will sloppily refer to self.foo as a variable, they aren't the same. Assigning to self.foo is actually just a shorthand for

setattr(self, 'foo', temp)

This is what allows you to define getters and setters for attributes. It would complicate the specification and implementation of the assignment expression if it had to work with attributes that have customized setters.

For instance, if the setter transforms the value that's being assigned, should the value of the assignment expression be the original value or the transformed value?

Variables, on the other hand, cannot be customized. Assigning to a variable always has the same, simple semantics, and it's easy for the expression to evaluate to the value that was assigned.

Similarly, you can't use the walrus operator with slice assignment. This isn't valid:

foo1[2:4] := foo2[1:3]
like image 102
Barmar Avatar answered Sep 21 '22 12:09

Barmar


Interestingly, the prohibition on walrussing object.attributes seems to be present only in Python's parser that parses text code into an abstract syntax tree (ast), which then would be compiled and executed. If you manually create an ast syntax tree with self.foo taking the place of var in (var := temp) and then compile or exec that tree, it compiles and executes just as you would intuitively expect it to.

So apparently the underlying functionality is there to allow walrus-assignment to object.attributes, they just chose not to let us use it, because they were worried it would make people write confusing code or something. Thanks a lot...

So anyway, an extreme (not at all recommended!) solution would be for you to do a bit of pre-compilation ast-surgery to splice your object.attribute targets into your walrus operators, and then it'd probably run as you expect. (I discovered this since I was already doing ast-surgery that replaced simple variables with object.attributes for other reasons, and I was happy to find that walrus assignment still worked!)

like image 34
JustinFisher Avatar answered Sep 17 '22 12:09

JustinFisher