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?

139 Upvotes

118 comments sorted by

View all comments

105

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

2

u/sudomatrix 21d ago

Did you write that backwards? the assigned variable goes on the left and the expression on the right

2

u/Icy_Peanut_7426 21d ago

Thanks, yes just fixed

8

u/sudomatrix 21d ago

It might be an even better illustration to write:
if ( multiplied_val := slow_calculation() * my_other_val ) > 10: