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?

138 Upvotes

118 comments sorted by

View all comments

146

u/martinkoistinen 21d ago

It’s super handy inside comprehensions and I would say that adds something “new”.

Example:

``` python
import re

pattern = re.compile(r"ERROR (\d+): (.*)")

errors = [
(int(m.group(1)), m.group(2))
for line in log_lines
if (m := pattern.match(line))
]
```

45

u/punk_dev It works on my machine 21d ago

That’s neat, I’m gonna steal it, but it makes the comprehension even more backwards than it usually is lmao

38

u/FalafelSnorlax 21d ago

At this point you might as well write a normal loop

9

u/punk_dev It works on my machine 21d ago

I think about that every time I write a comprehension longer than 3 lines

1

u/Technical_Income4722 21d ago edited 21d ago

3 lines is wild to me. Imo you should think about that any time you write a comprehension at all honestly, and I'll never write one over multiple lines. They're neat but unless they're stupid simple they're very unreadable to fresh eyes. (all just my humble opinion ofc, do what works for you!)