HPAC / matchpy

A library for pattern matching on symbolic expressions in Python.
MIT License
164 stars 25 forks source link

Overridable node visitors instead of typed-nodes in expression trees #75

Open Upabjojr opened 11 months ago

Upabjojr commented 11 months ago

The current MatchPy implementation defines expression trees and allows expression trees to be overloaded by external library (as it is done in SymPy's connector to MatchPy). Unfortunately, the current MatchPy implementation relies on types and isinstance( ) calls to determine the expression node. For example:

The first one is quite tricky in SymPy because it needs to define a new class that is both a MatchPy and SymPy object.

There are other approaches to expression tree that do not defined typed nodes (i.e. classes that represent a particular type of node). For example, protosym has a unique class to define many types of nodes.

Does it make sense to create an overridable method is check whether a node is a wildcard/operation/associative operation/commutative operation/etc... so that custom libraries may define their way to visit their expression trees?

wheerd commented 11 months ago

For operations, matchpy uses the ABCMeta metaclass which allows registering any type as a subclass: https://docs.python.org/3/library/abc.html#abc.ABCMeta.register I don't know if there is a need for doing the same for wildcards, maybe it is enough to create a subclass that is both a sympy class and a subclass of Wildcard. I would rather not do a big change to how expression trees function in matchpy.

Upabjojr commented 11 months ago

For operations, matchpy uses the ABCMeta metaclass which allows registering any type as a subclass:

That's the limitation, there are many examples of libraries using a single class for all expression trees. I'm not sure you can handle those cases unless you really hack/override python's typing methods.