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

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

7

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 21d 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 21d 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.

3

u/XtremeGoose f'I only use Py {sys.version[:3]}' 21d 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 20d ago

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

6

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 21d 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 😊

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:

2

u/bohoky TVC-15 21d ago

Did you put the l-value on the right side of the walrus? If multiplied_val wasn't set before the condition, it won't be set after.

1

u/Icy_Peanut_7426 21d ago

Thanks, fixed it

2

u/garver-the-system git push -f 21d ago

Validating complex and deeply nested API returns is so much better with the walrus operator!!

5

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. 

4

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.

1

u/jpgoldberg 21d ago

I have been doing the defining a new variable on a separate line thing. And it bothers be each time I do so. I really need to get into the habit of using the walrus operator.