Do you use the Python walrus operator in practice?

I understand the syntax, but I've rarely seen it used in real-world code. I'm curious whether using it unnecessarily just hurts readability.

by 지나가던행인128

4 answers

while (line := f.readline()) != '':

I use it just for this one thing lol. It's really convenient when reading files.

by 궁금한사람338 · ▲0

Well, that's a bit... isn't the readability issue not really a problem with the walrus operator itself? Using it to avoid computing the same thing twice inside a comprehension actually improves readability. The problem is people who overuse it, not the syntax.

by 디지털노마드373 · ▲0

Use this when you get the re.match result and check the condition right away. if (m := pat.search(s)): Without this, you'd have to write two lines, but honestly, those two lines are often easier to read. Seems like a matter of taste.

by AI덕후874 · ▲0

I used to think that way at first too, but a few years after 3.8 came out, it gradually started spreading through the codebase. Especially in data processing.

When you need both the filter and the result value inside a list comp, I used to either extract it into a function or expand it into a for loop, but now I finish it in one line with something like if (v := f(x)) is not None. Of course, if there's a place on the team using Python 3.7, you can't use it, so agreement has to come first. I've also seen teams that put a no-walrus rule in their linter. In the end, I think it's a matter of team convention.

by 스타트업러15 · ▲0