|
|
Log in / Subscribe / Register

"Structural pattern matching" for Python, part 2

"Structural pattern matching" for Python, part 2

Posted Sep 2, 2020 14:19 UTC (Wed) by tnemeth (guest, #37648)
In reply to: "Structural pattern matching" for Python, part 2 by NAR
Parent article: "Structural pattern matching" for Python, part 2

Indeed. I discussed this issue with a friend who has developed in Scala. He told me that in what he understood from the article -- and what I completely missed -- is that if I want error reporting, I may simply have to use

case x:
print("error: ", str(x))

an not use the `_` (which isn't meant to be used).


to post comments

"Structural pattern matching" for Python, part 2

Posted Sep 3, 2020 13:22 UTC (Thu) by hartb (subscriber, #96640) [Link] (1 responses)

I guess you still have the object-to-be-matched handy:
match t:
    ...
    case _:
        print("error: ", str(t))

"Structural pattern matching" for Python, part 2

Posted Sep 4, 2020 16:04 UTC (Fri) by mathstuf (subscriber, #69389) [Link]

I was worried about the same thing too, but the walrus operator saves you in this related case as well:
match t := some_expr():
    case ...:
    case _:
        # use t
Though I don't like the locality mismatch here. For a large (probably considered un-Pythonic) match, your variable assignment is far away when it could be right next to it. You also have to consider that `t` is now always assigned to rather than just in the catch-all case.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds