(no title)
ghewgill | 7 months ago
if m := re.match(pattern1, line):
do_stuff(m.group(1))
elif m := re.match(pattern2, line):
do_other_stuff(m.group(2))
elif m := re.match(pattern3, line):
do_things(m.groups())
else:
...
sfink|7 months ago
But the walrus is good even in the absence of a series of matches. It is quite common to need to know more than the boolean "did this match or not?", and so to my eye it is much cleaner to have one line doing the test and the next lines using the results. I don't care about saving characters or even lines. `m = ...match...` immediately followed by `if m:` feels like overhead for the sake of the programming language's limitations; it's extraneous to what I want to express.
Also, I assert that the pattern is better for correctness. It's like Rust's `if let Some(foo) = f() { ... }` pattern: guard on a certain condition, then use the results if that condition is true.
invites injecting code in between the assignment and the test. They're two different things to the reader. And it's not as clear that `v` should only be used in the consequent body. says exactly what it means: `f()` may return a truthy value. If it does, do something with it.pansa2|7 months ago