Antoine Pitrou wrote:
On Mon, 23 Nov 2020 16:15:12 -0000 "Brian Coleman" firstname.lastname@example.org wrote:
Furthermore, Python has a regular expression module which implements it's own DSL for the purpose of matching string patterns. Regular expressions, in a similar way to pattern matching, allow string patterns to be expressed in a concise and declarative manner. Uh, without regular expressions, a lot of functions would be massively
more complicated and annoying to write. However, your example shows that pattern matching barely makes common code shorter (admittedly, on this _one_ example, but that's the one you chose ;-)). While I agree that regular expressions are far less Pythonic than the proposed variant of pattern matching, they also have a tremendously better cost/benefit ratio, IMHO. Regards Antoine.
In my opinion, the object oriented solution to this problem is to use the visitor pattern. The solution using the visitor pattern is almost twice the length of the other solutions. Pattern matching is certainly no worse than the solution using a chain of `isinstance` checks in this case.
However as the patterns to be checked against a candidate object become more complex, I believe that the pattern matching solution will retain the same level of elegance and obviousness that it possesses in this example, whereas the solution involving a chain of comparisons will quickly degrade in terms of obviousness.