Search code examples
pythonpython-3.xsyntaxlanguage-designpython-assignment-expression

Can any usage of the assignment operator technically be replaced with the walrus operator surrounded by parentheses?


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?


Solution

  • I think it should work anywhere.

    • You can have an assignment anywhere that a statement is allowed.
    • An expression can be used as a statement.
    • A walrus assignment is an expression.

    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