Skip to main content

effective and graceful pattern matching for original python

Project description

License PyPI version

Tail call optimization(TCO) has been removed from this package for following reasons:

  1. TCO is easy to implement.
  2. Guaranteeing TCO dynamically in any situations is really expensive.

If you do want to use TCO in Python, check

The documents have been migrated to README now:


These are all you need to import.

from pattern_matching import var, _, T, t, when, Match, overwrite

Type Matching

@when(var[T == int])
# T means the type would be capture.
def f(v, type_of_v):
    print(v, type_of_v)

# => (1, int)

Remark: Using Match is similar to when/overwrite:

m = Match(1)
res =[T == int])
if res:
    [a, b] = res.get
    assert [a, b] == [1, int]

If the pattern matched, returns a Result object.

class Result:
    __slots__ = 'get'

    def __init__(self, _):
        self.get = _

Otherwise the return is None.

Value Matching

@when(_ == 1)
def f():
    return 12

@when(_ == 2)
def f():
    return 0

def f(arg):
    return arg ** 3

f(1), f(2), f(3) # => 12, 0, 27

Wildcard for types

@when(var[t == float])
# the lowercase, "t", which indicates that the type just be matched without capture.
def f(v):
# => 1.0

Wildcard for values

def f():
    return 1
f(1) == f("...") == f(1e-3)
# => True

Type Boundary

class MyList(list):
from collections import Iterable

@when(var[Iterable <= T <= MyList]
    .when(lambda x: 1 in x)
def f(x, T):
    return (x, T)

f([1, 2, 3])
# => ([1, 2, 3], list)

f({1, 2, 3})
# => UnsolvedCase: No entry for args<({1, 2, 3},)>, kwargs:<{}>

Overloading functions

Overloading functions are introduced through the following simple cases:

@overwrite(_ == [])
def summary():
    return 0

@when([var[int], *(_== [])])
def summary(head):
    return head

@when([var[int], *var[list]])
def summary(head, tail):
    return head + summary(tail)

summary([1, 2, 3])
# => 6

Note that above code is definitely useless for it doesn’t use tail call optimization.

Union Type

@when(var[(t == int) | (t == str)])
def disp(x):
disp(1) # => 1
disp('1') # => '1'

Intersection Type

class A:
class B:
class C(A, B):

@when(_[(T == A) | (T == B)])
def disp(ty):
disp(C()) # => <class __main__.C>

Difference Type

class A:
class B:
class C(A, B):

@when(_[T != A])
def disp(ty):
disp(C()) # => <class __main__.C>
disp(B()) # => <class __main__.B>

# => UnsolvedCase: No entry for args<(<__main__.A object at ...>,)>, kwargs:<{}>

Type Contracts

You can apply .when(predicate) methods on pattern_matching.T/t .

To avoid subclassing.

class A:
class B:
class C(A, B):

@overwrite(_[T.when(lambda _: not issubclass(_, A))])
def disp(ty):
disp(C()) # => <class __main__.C>
# => UnsolvedCase: No entry for args<(<__main__.C object at ...>,)>, kwargs:<{}>

Match Argument Numbers

def f(g):
    return g(1, 2)

f(lambda a, b: a + b) # => 3
f(lambda a, b, c: a + b)
# => UnsolvedCase: No entry for args<(<function <lambda> at ...>,)>, kwargs:<{}>

class F:
    def apply(self, arg):
        return arg + 1

def f2(g):
    return g(1)

f2(lambda a, b: a + b)
# => UnsolvedCase: No entry for args<(<function <lambda> at ...>,)>, kwargs:<{}>
f2(F().apply) # => 2

Project details

Download files

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

Filename, size & hash SHA256 hash help File type Python version Upload date
pattern_matching-1.0.1-py3-none-any.whl (6.5 kB) Copy SHA256 hash SHA256 Wheel 3.6

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN SignalFx SignalFx Supporter DigiCert DigiCert EV certificate StatusPage StatusPage Status page