matchpy.functions module¶
This module contains various functions for working with expressions.
 With
substitute()
you can replace occurrences of variables with an expression or sequence of expressions.  With
replace()
you can replace a subexpression at a specific position with a different expression or sequence of expressions.  With
replace_many()
works the same asreplace()
, but you can replace multiple positions at once.  With
replace_all()
you can apply a set of replacement rules repeatedly to an expression.  With
is_match()
you can check whether a pattern matches a subject expression.

substitute
(expression: Union[matchpy.expressions.expressions.Expression, matchpy.expressions.expressions.Pattern], substitution: matchpy.expressions.substitution.Substitution, sort_key: Optional[Callable[matchpy.expressions.expressions.Expression, Any]] = None) → Union[matchpy.expressions.expressions.Expression, List[matchpy.expressions.expressions.Expression]]¶ Replaces variables in the given expression using the given substitution.
>>> print(substitute(f(x_), {'x': a})) f(a)
If nothing was substituted, the original expression is returned:
>>> expression = f(x_) >>> result = substitute(expression, {'y': a}) >>> print(result) f(x_) >>> expression is result True
Note that this function returns a list of expressions iff the expression is a variable and its substitution is a list of expressions. In other cases were a substitution is a list of expressions, the expressions will be integrated as operands in the surrounding operation:
>>> print(substitute(f(x_, c), {'x': [a, b]})) f(a, b, c)
If you substitute with a
Multiset
of values, they will be sorted:>>> replacement = Multiset([b, a, b]) >>> print(substitute(f(x_, c), {'x': replacement})) f(a, b, b, c)
Parameters:  expression – An expression in which variables are substituted.
 substitution – A substitution dictionary. The key is the name of the variable, the value either an expression or a list of expression to use as a replacement for the variable.
Returns: The expression resulting from applying the substitution.

replace
(expression: matchpy.expressions.expressions.Expression, position: Sequence[int], replacement: Union[matchpy.expressions.expressions.Expression, List[matchpy.expressions.expressions.Expression]]) → Union[matchpy.expressions.expressions.Expression, List[matchpy.expressions.expressions.Expression]]¶ Replaces the subexpression of
expression
at the givenposition
with the givenreplacement
.The original
expression
itself is not modified, but a modified copy is returned. If the replacement is a list of expressions, it will be expanded into the list of operands of the respective operation:>>> print(replace(f(a), (0, ), [b, c])) f(b, c)
Parameters:  expression – An
Expression
where a (sub)expression is to be replaced.  position – A tuple of indices, e.g. the empty tuple refers to the
expression
itself,(0, )
refers to the first child (operand) of theexpression
,(0, 0)
to the first child of the first child etc.  replacement – Either an
Expression
or a list ofExpression
s to be inserted into theexpression
instead of the original expression at thatposition
.
Returns: The resulting expression from the replacement.
Raises: IndexError
– If the position is invalid or out of range. expression – An

replace_all
(expression: matchpy.expressions.expressions.Expression, rules: Iterable[matchpy.functions.ReplacementRule], max_count: int = inf) → Union[matchpy.expressions.expressions.Expression, Sequence[matchpy.expressions.expressions.Expression]]¶ Replace all occurrences of the patterns according to the replacement rules.
A replacement rule consists of a pattern, that is matched against any subexpression of the expression. If a match is found, the replacement callback of the rule is called with the variables from the match substitution. Whatever the callback returns is used as a replacement for the matched subexpression. This can either be a single expression or a sequence of expressions, which is then integrated into the surrounding operation in place of the subexpression.
Note that the pattern can therefore not be a single sequence variable/wildcard, because only single expressions will be matched.
Parameters:  expression – The expression to which the replacement rules are applied.
 rules – A collection of replacement rules that are applied to the expression.
 max_count – If given, at most max_count applications of the rules are performed. Otherwise, the rules are applied until there is no more match. If the set of replacement rules is not confluent, the replacement might not terminate without a max_count set.
Returns: The resulting expression after the application of the replacement rules. This can also be a sequence of expressions, if the root expression is replaced with a sequence of expressions by a rule.

replace_many
(expression: matchpy.expressions.expressions.Expression, replacements: Sequence[Tuple[Sequence[int], Union[matchpy.expressions.expressions.Expression, List[matchpy.expressions.expressions.Expression]]]]) → Union[matchpy.expressions.expressions.Expression, List[matchpy.expressions.expressions.Expression]]¶ Replaces the subexpressions of expression at the given positions with the given replacements.
The original expression itself is not modified, but a modified copy is returned. If the replacement is a sequence of expressions, it will be expanded into the list of operands of the respective operation.
This function works the same as
replace
, but allows multiple positions to be replaced at the same time. However, compared to just replacing each position individually withreplace
, this does work when positions are modified due to replacing a position with a sequence:>>> expr = f(a, b) >>> expected_result = replace_many(expr, [((0, ), [c, c]), ((1, ), a)]) >>> print(expected_result) f(c, c, a)
However, using
replace
for one position at a time gives the wrong result:>>> step1 = replace(expr, (0, ), [c, c]) >>> print(step1) f(c, c, b) >>> step2 = replace(step1, (1, ), a) >>> print(step2) f(c, a, b)
Parameters:  expression – An
Expression
where a (sub)expression is to be replaced.  replacements –
A collection of tuples consisting of a position in the expression and a replacement for that position. With just a single replacement pair, this is equivalent to using
replace
:>>> replace(a, (), b) == replace_many(a, [((), b)]) True
Returns: The resulting expression from the replacements.
Raises: IndexError
– If a position is invalid or out of range or if you try to replace a subterm of a term you are already replacing.
 expression – An

is_match
(subject: matchpy.expressions.expressions.Expression, pattern: matchpy.expressions.expressions.Expression) → bool¶ Check whether the given subject matches given pattern.
Parameters:  subject – The subject.
 pattern – The pattern.
Returns: True iff the subject matches the pattern.

class
ReplacementRule
(pattern, replacement)¶ Bases:
tuple

__getnewargs__
()¶ Return self as a plain tuple. Used by copy and pickle.

static
__new__
(_cls, pattern, replacement)¶ Create new instance of ReplacementRule(pattern, replacement)

__repr__
()¶ Return a nicely formatted representation string

_asdict
()¶ Return a new OrderedDict which maps field names to their values.

classmethod
_make
(iterable, new=<builtin method __new__ of type object>, len=<builtin function len>)¶ Make a new ReplacementRule object from a sequence or iterable

_replace
(**kwds)¶ Return a new ReplacementRule object replacing specified fields with new values

pattern
¶ Alias for field number 0

replacement
¶ Alias for field number 1


replace_all_post_order
(expression: matchpy.expressions.expressions.Expression, rules: Iterable[matchpy.functions.ReplacementRule]) → Union[matchpy.expressions.expressions.Expression, Sequence[matchpy.expressions.expressions.Expression]]¶ Replace all occurrences of the patterns according to the replacement rules.
A replacement rule consists of a pattern, that is matched against any subexpression of the expression. If a match is found, the replacement callback of the rule is called with the variables from the match substitution. Whatever the callback returns is used as a replacement for the matched subexpression. This can either be a single expression or a sequence of expressions, which is then integrated into the surrounding operation in place of the subexpression.
Note that the pattern can therefore not be a single sequence variable/wildcard, because only single expressions will be matched.
Parameters:  expression – The expression to which the replacement rules are applied.
 rules – A collection of replacement rules that are applied to the expression.
 max_count – If given, at most max_count applications of the rules are performed. Otherwise, the rules are applied until there is no more match. If the set of replacement rules is not confluent, the replacement might not terminate without a max_count set.
Returns: The resulting expression after the application of the replacement rules. This can also be a sequence of expressions, if the root expression is replaced with a sequence of expressions by a rule.