|
|
Log in / Subscribe / Register

"Structural pattern matching" for Python, part 1

"Structural pattern matching" for Python, part 1

Posted Aug 5, 2020 18:10 UTC (Wed) by donacthulhuote (guest, #136577)
Parent article: "Structural pattern matching" for Python, part 1

Ignoring the fact I wouldn't be able to use this until wherever I'm working gets to python 3.10, I really like the proposal. The only language I know with similar capabilities is Rust, but once you get used to the syntax (which is admittedly a slight hurdle, and which people far smarter than me are working out in this case), it makes for really clean code in a number of cases (to my eyes). It also feels like a better abstraction for a large number of if statements in the cases where what you really want is, well, to match your object to something.

My only consternation is that a large part of the power in rust is that you're forced to deal with all cases, and compiler will help you along if you're missing anything. Python being dynamic doesn't have that luxury, and I wonder how much utility is lost thereby.


to post comments

"Structural pattern matching" for Python, part 1

Posted Aug 5, 2020 18:15 UTC (Wed) by re:fi.64 (subscriber, #132628) [Link] (1 responses)

Well, type hint checkers can be updated to handle the new pattern matching syntax.

"Structural pattern matching" for Python, part 1

Posted Aug 5, 2020 21:33 UTC (Wed) by NYKevin (subscriber, #129325) [Link]

I think that will depend to some extent on the ability of the type linter to produce refutations. If the type linter cannot prove that a pattern (or series of patterns) is irrefutable, but it also cannot provide a sample refutation to those patterns, then the developer will be tempted to shove in a case _: pass clause "to make the type linter shut up." Depending on the circumstances, this may or may not be safe, and it certainly won't be future proof (if the patterns are later changed in such a way that they really do become refutable, then the type linter won't see anything wrong with the match).

On the other hand, if the type linter can guarantee that it will always be able to come up with a specific refutation, then it may actually help catch bugs much earlier in development. Given the complexity of Python's dynamic typing system, I think this is still a bit of an open problem, although I welcome corrections on this point.


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