santinic / pampy

Pampy: The Pattern Matching for Python you always dreamed of.
MIT License
3.51k stars 125 forks source link

Add any behaiour to match function with callables #16

Closed stevenheidel closed 5 years ago

stevenheidel commented 5 years ago

This is a relatively simple way to allow people to add custom patterns on any type, or even combinations of patterns.

Previously pampy allowed a pattern to be a lamba which returns a boolean. This extends that to allow a lambda which returns both a boolean (for whether there was a match) and a list (for the matched values).

For instance with the datetime type, it would be difficult to create a pattern for this because the datetime constructor does type checking:

>>> datetime(2018, _, _)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type UnderscoreType)

In the tests I give an example of a datetime pattern datetime_p which works as expected:

match(var, datetime_p(2018, _, _), lambda month, day: f'{month}/{day} in 2018')

Similarly you can create more advanced patterns that are combinations of other smaller patterns (like matching one pattern OR another pattern) and could satisfy the multiple guards suggestion from #10

PS. The existing lambda behavior was undocumented so I didn't write any docs for this either. Would be happy to add that though.

santinic commented 5 years ago

Nice! Yeah, we need a paragraph in the README. I hope to write an article to illustrate the amazing ways to use Pampy you have introduced. With dataclasses and these lambdas, it's now the cleanest pattern-matching I've seen for python.