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

1

9

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)
Impasse answered 24/7, 2021 at 4:19 Comment(2)
I’m voting to close this question because Stack Overflow is not intended to replace existing documentation.Triode
@KarlKnechtel. A significant portion of the more helpful questions here are exactly about existing documentation. Questions about the existence of stuff are generally harder to find without the right terms. In this case, if I wasn't familiar with the PEP, I would not have even known where to start looking. It's certainly not answered directly in the official docs anywhere.Inexplicable
I
11

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.

Inexplicable answered 24/7, 2021 at 4:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.