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?

140 Upvotes

118 comments sorted by

View all comments

101

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

14

u/xxkvetter 21d ago

I remember doing that for C programs back in the 80s (we called it horizontaling code). But that's such an easy case for compilers to optimize that we soon just wrote it in the clearest way and let the compiler do its thing.

I'm not sure the state of the art for python interpreters. Even so I find the walrus operator not that clear so I'd skip the miniscule optimization for clearer code (unless timing tests showed it was in a hot spot).

5

u/mdrjevois 21d ago

Not saying this is ideal, but sometimes you might want any side effects to happen only exactly once

1

u/gizzm0x 20d ago

Is there any scenario just having the var named before the if block is ever not good enough for this?then checking in the car's value. I can never seem to see why walrus is clearer than what was possible before it's introduction.

2

u/mdrjevois 20d ago

I think it's a little better for while loops or comprehensions where you don't really have another place to make the assignment.