DEV Community

Discussion on: Python SnakeBytes: Unpacking

Collapse
 
codemouse92 profile image
Jason C. McDonald

I don't know that it was. It does simplify some conditional statements by moving the assignment into the comparison expression.

if value := will_this_return():
    print(f"Do something with {value}")

Without the walrus operator, we'd have to add additional code and complexity for no immediate benefit:

value = will_this_return()
if value:
    print(f"Do something with {value}")

That's a simplistic example, of course, but it demonstrates a situation that more robust code sometimes encounters.

I've learned not to dismiss a tool or feature as "unnecessary" just because I can't think of a use case myself; doing so would be quite presumptive on my part!

PEP 572 includes some notes by Tim Peters on which situations are well-suited to the walrus operator, and which are not.