Search code examples
pythonpython-3.8walrus-operator

Can you combine the addition assignment ( += ) operator with the walrus operator ( := ) in Python?


This is the code I write right now:

a = 1
if (a := a + 1) == 2:
  print(a)

I am wondering if something like this exists:

a = 1
if (a +:= 1) == 2:
  print(a)

Solution

  • PEP-527 defined the new walrus operator. The section discussing differences between assignment statements and expressions explicitly states:

    • Augmented assignment is not supported:

      total += tax  # Equivalent: (total := total + tax)
      

    In the section explaining why = is still necessary with :=, we find:

    The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

    This strongly implies that there is no intention of supporting a merge of walrus and in-place operators of any kind.