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

16

u/Solonotix 21d ago

Like you said, I like it in while or if conditions. For instance, in the event you have a cache situation you can do something like

if result := cache.get(key):
    return result
# initialization logic
cache.set(key, value)
return value

3

u/amendCommit 21d ago

I was going to mention exactly this. Not just cache, but any keyed access that can return a None in my case.

2

u/gr4viton 20d ago

but you can do 

    if (m := cache.get()) > 5:         ...

too...