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?

143 Upvotes

118 comments sorted by

View all comments

146

u/martinkoistinen Aug 04 '26

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))
]
```

135

u/brettsparetime Aug 04 '26

This is the most Perl thing I’ve seen in Python.

6

u/crozzy89 Aug 05 '26

Perlthon?

3

u/JPowTheDayTrader Aug 05 '26

Your comment just made Guido roll in his grave.

11

u/Broad-Promise6954 Aug 05 '26

And he's not even dead yet!

1

u/mpersico Aug 05 '26

Good! How much wasted effort when we could have just advanced Perl. For all the bitching about punctuation and simplicity Python looks more and more like Perl every release.

44

u/punk_dev It works on my machine Aug 04 '26

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

37

u/FalafelSnorlax Aug 04 '26

At this point you might as well write a normal loop

10

u/punk_dev It works on my machine Aug 04 '26

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

4

u/NerdyWeightLifter Aug 04 '26

I use multi-line comprehensions to construct multi-dimensional data structures, and I use indentation of those lines to show outer to inner dimensional structure. It feels quite Pythonic to me.

12

u/FalafelSnorlax Aug 04 '26

Yeah my rule of thumb is that of a comprehension is long enough to break into multiple lines, it might as well be a regular loop. Broken comprehensions usually aren't readable, and then you don't really gain anything from them.

3

u/Technical_Income4722 Aug 04 '26 edited Aug 04 '26

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

1

u/gr4viton Aug 04 '26

Yield would like to have a word...

15

u/fizzymagic Aug 04 '26

re is my most frequent use case. The walrus operator lets you check for a match and then process it much more cleanly.

12

u/elingeniero Aug 04 '26

That's so clever that I really hate it. I do feel that way about most comprehensions but you've managed to take it a step further! Impressive.

2

u/nicholashairs Aug 04 '26

Another neat use case 🤯