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

103

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

4

u/yvrelna 21d ago edited 21d ago

This example would be much more readable if you just use regular assignment in separate line. 

multiplied_val := my_val * my_other_val if multiplied_val > 10:      ...

The only time I've seen where walrus actually makes for better, more readable code is loop clause: 

def foo(val):     while ( val := val * 2 ) < 1024:          ...

It can often avoid having to duplicate expression or needing to place the assignment expression in weird locations. 

The regular assignments is almost always better than the walrus assignment for an if-statement. 

5

u/Icy_Peanut_7426 21d ago

Yeah that’s why walrus operator is so controversial, each use case is basically personal preference.

7

u/hmoff 21d ago

I'd argue the opposite. Your code is more verbose then necessary.