|
|
Log in / Subscribe / Register

"Structural pattern matching" for Python, part 2

"Structural pattern matching" for Python, part 2

Posted Sep 2, 2020 13:00 UTC (Wed) by tnemeth (guest, #37648)
Parent article: "Structural pattern matching" for Python, part 2

> The value assigned to `_` is uninteresting [...]

I'm sorry to disagree here but IHMO the "default:" case can need to access the `_` value, for error reporting...


to post comments

"Structural pattern matching" for Python, part 2

Posted Sep 2, 2020 14:08 UTC (Wed) by NAR (subscriber, #1313) [Link] (3 responses)

In Erlang/Elixir world if I want to print out that value for error reporting, I don't use the _, but give some meaningful name to that variable. Of course, _ doesn't really mean it's "uninteresting", it means that the variable is intentionally not used.

"Structural pattern matching" for Python, part 2

Posted Sep 2, 2020 14:19 UTC (Wed) by tnemeth (guest, #37648) [Link] (2 responses)

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

"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