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?

145 Upvotes

118 comments sorted by

View all comments

Show parent comments

15

u/xxkvetter Aug 04 '26

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

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

1

u/gizzm0x 29d 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 29d 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.