zspec
A Python library for writing and combining business rules using the Specification pattern, with adapters to apply the same rule to SQL, MongoDB, Django, SQLAlchemy, Polars, and Pandas.
zspec is a Python library that helps developers write and combine business rules in a structured way using a pattern called the Specification pattern. The core idea is that each rule is a small class with a single job: check whether a given object meets a condition. You can then combine rules using familiar operators like & (and), | (or), ^ (exclusive or), and ~ (not) to build more complex checks from simple ones without writing a new class for each combination.
Rather than defining a class for every rule, zspec also lets you declare rules inline using field comparisons or short lambda functions. Either approach produces the same kind of composable object, so you can mix and match both styles in the same project.
One practical feature is that the same specification can be translated into query syntax for multiple data backends. The library ships adapters for SQL, MongoDB, Django query objects, SQLAlchemy, Polars, and Pandas. You describe a rule once and apply it to whichever storage or data-processing layer your project uses.
You can also serialize a specification to a Python dictionary and reload it from that dictionary later, which means rules can be stored in configuration files or databases. A built-in explain() function shows a pass or fail result for every node in a composed rule, making it easier to debug why a complex condition is or is not matching a particular object.
The library requires Python 3.12 or higher and has no mandatory external dependencies. Optional extras add the specific backend adapters for databases and data-frame libraries. It is published on PyPI and installable with a single pip command.
Where it fits
- Write a reusable "active user" rule once and apply it to both your SQL database and a Pandas dataframe without changing the rule.
- Store filtering rules as JSON in a database so non-engineers can update them without touching code.
- Debug why a complex composed rule is failing by calling explain() to see which sub-condition failed.
- Build an e-commerce product filter that chains price, category, and stock rules using & and | operators.