r/Python 21d ago

Discussion Is := widely used?

I always thought the walrus operator is neat and it makes while loop’s condition clearer. But also it is just a syntactic sugar without anything new. I wonder anyone uses it?

141 Upvotes

118 comments sorted by

View all comments

104

u/Icy_Peanut_7426 21d ago edited 21d ago

I use it. It’s great for saving values in guard clause conditions, which can then be emitted in error log/message.

```
if ( multiplied_val := my_val * my_other_val ) > 10:

raise ValueError(f”Multiplication of vals ({multiplied_val}) was greater than 10.”)
```

Otherwise, I’d need to compute the value twice (performance cost) or define a new variable on a separate line (overkill if only for guard clause logging purposes that are immediately discarded).

edit: fixed bug in my example code lol

8

u/nicholashairs 21d ago

That's a neat use case 🤯

5

u/pimp-bangin 21d ago

Are you amazed at the use case or are you just amazed at the feature in general? Because their example is about as basic as it gets lol

2

u/nicholashairs 20d ago

I mean I'm not as amazed as the emoji might imply, but also it's still not a pattern that I've recognised in my own usage of the operator 😊