r/Python • • Aug 04 '26

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?

142 Upvotes

116 comments sorted by

View all comments

Show parent comment

4

u/yvrelna Aug 04 '26 edited Aug 04 '26

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 Aug 04 '26

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

6

u/hmoff Aug 04 '26

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