Skip to main content

Functional-style recursive pattern matching in Python. Crazy stuff.

Project description

Functional-style recursive pattern matching in Python. Crazy stuff.

Install

pip install patmat

Usage

Pattern matching with patmat:

>>> from patmat import *
>>> Mimic({(1, Val('k')): (3, Val('v'))}).match({(1, 2): (3, 4)})
{'k': 2, 'v': 4}

Multiple dispatch generic functions:

>>> from patmat import *
>>>
>>> @case
>>> def func(match, l=[Val('head'), ..., 3, Val('tail')]):
...     print('a list with a head {} and a tail {}'.format(match.head, match.tail))
>>>
>>> @case
>>> def func(match, l=Val('item')):
...     print('an item {}'.format(match.item))
>>>
>>> func([1, 2, 3, 4])
a list with a head 1 and a tail 4
>>> func(5)
an item: 5

More dispatch examples:

>>> @case
>>> def func(_, x=int):
...     print('Do something with an integer.')
>>>
>>> @case
>>> def func(_, x=float):
...     print('Do something with a float.')
>>>
>>> func(1)
Do something with an integer
>>> func(1.0)
Do something with a float

Matches list, tuple, dict, types, classes with attributes. Brace yourself for the power of recursive pattern matching:

>>> from patmat import *
>>> m = Mimic([
...     1, Type(int, Val(2)),
...     Mimic(a=3, b=[4, Val(5), 6], c=Val(7)),
...     Val(8), {Val(9): 10, Val(11): 12},
... ])
>>> class A:
...     __init__ = lambda self, **kwargs: self.__dict__.update(kwargs)
>>> m.match([1, 2, A(a=3, b=[4, 5, 6], c=7), 8, {9: 10, 11: 12}])
{2: 2, 5: 5, 7: 7, 8: 8, 9: 9, 11: 11}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

patmat-1.0.1.tar.gz (5.7 kB view details)

Uploaded Source

File details

Details for the file patmat-1.0.1.tar.gz.

File metadata

  • Download URL: patmat-1.0.1.tar.gz
  • Upload date:
  • Size: 5.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for patmat-1.0.1.tar.gz
Algorithm Hash digest
SHA256 bcc55351e329b7ce89d9df4fe7e6bee4a7d8f57ba185f8af0aaad0751bf28502
MD5 386af56bdf3d38c06752c7581139400a
BLAKE2b-256 0434d988505c225efdd87ae8853b8cd01babf25d690002ac7f4af96e208f0681

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page