santinic / pampy

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

Better looking nested patterns? #24

Open senpos opened 5 years ago

senpos commented 5 years ago

Hi,

Is there any better way achieving this?

from pampy import match, _

test_items = [5, '5', [5], 'not a digit']

for x in test_items:
    result = match(x,
        str, lambda x: match(x,
                           str.isdigit, lambda x: int(x),
                           _, 0
                        ),
        int, x,
        _, 0
    )
    print(f'{x} ({type(x).__name__}) -> {result}')

It is hard to describe what we want to achieve in words, but it's easy to see by example:

5 -> 5
'5' -> 5
'not a digit' -> 0
[1] -> 0

It looks over-complicated.