Skip to main content

A pattern matching library.

Project description

A pattern matching libary for python.

Work in progress

Test coverage Build status of the master branch Documentation Status


This package implements pattern matching in python. It is similar to the implementation in Mathematica or Haskell.


Expressions and patterns both have a tree structure. Expressions consist of symbols (leafs) and operations (internal nodes):

>>> from matchpy.expressions import Operation, Symbol, Arity
>>> f ='f', Arity.binary)
>>> a = Symbol('a')
>>> print(f(a, a))
f(a, a)

Patterns are expressions which can additionally contain variables and wildcards. Variables can give a name to a node of the pattern so that it can be accessed later. Wildcards are placeholders that stand for any expression. Usually, the two are used in combination:

>>> from matchpy.expressions import Variable
>>> x ='x')
>>> print(f(a, x))
f(a, x_)

However, unnamed wildcards can also be used:

>>> from matchpy.expressions import Wildcard
>>> w =
>>> print(f(w, w))
f(_, _)

Or a more complex expression can be named with a variable:

>>> print(Variable('y', f(w, a)))
y: f(_, a)

In addition, it supports sequence wildcards that stand for multiple expressions:

>>> z ='z')
>>> print(f(z))


Matches are given in the form of substitutions, which are a mapping from variable names to expressions:

>>> from matchpy.matching.one_to_one import match
>>> y ='y')
>>> b = Symbol('b')
>>> expression = f(a, b)
>>> pattern = f(x, y)
>>> substitution = next(match(expression, pattern))
>>> substitution
{'x': FrozenSymbol('a'), 'y': FrozenSymbol('b')}

Replacing the variables in the pattern according to the substitution will yield the original subject expression:

>>> from matchpy.functions import substitute
>>> original, _ = substitute(pattern, substitution)
>>> print(original)
f(a, b)

Project details

Download files

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

Files for matchpy, version 0.1.2
Filename, size File type Python version Upload date Hashes
Filename, size matchpy-0.1.2-py3-none-any.whl (54.9 kB) File type Wheel Python version 3.5 Upload date Hashes View
Filename, size matchpy-0.1.2.tar.gz (79.0 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page