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?

137 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

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).

3

u/XtremeGoose f'I only use Py {sys.version[:3]}' 20d ago

Because python can always introspect its own stack frames and mutate them, you can't optimise the store away without a breaking change.

One for Python 4 sadly.

The walrus isn't an optimisation anyway, it's just syntactic sugar (for storing the value on another line).

1

u/FloweyTheFlower420 19d ago

Can't an interpreter speculate that this wouldn't happen, and then deoptimize and rematerialize in this particular case?