zspec
Composable specification pattern for Python 3.12+.
Documentation · PyPI · GitHub
Install
pip install zspec
Quick start
from dataclasses import dataclass
from zspec import Specification
@dataclass
class Product:
price: int
in_stock: bool
# Define rules as classes
class InStock(Specification[Product]):
__slots__ = ()
def is_satisfied_by(self, p: Product) -> bool:
return p.in_stock
class MinPrice(Specification[Product]):
__slots__ = ("threshold",)
def __init__(self, threshold: int) -> None:
self.threshold = threshold
def is_satisfied_by(self, p: Product) -> bool:
return p.price >= self.threshold
# Compose with &, |, ^, ~
eligible = InStock() & MinPrice(100)
product = Product(price=200, in_stock=True)
assert eligible(product)
Or skip the class boilerplate:
# Field comparisons
spec = Specification[Product].matching(price__gte=100, in_stock=True)
# Lambda predicates
spec = Specification[Product].matching(
lambda p: p.price > 100,
lambda p: p.in_stock,
)
Why zspec?
| Composable | & | ^ ~ — build complex rules from simple ones without new classes |
| Zero dependencies | Standard library only. Optional extras for SQLAlchemy, Django, Polars, and Pandas |
| Type-safe | Generic Specification[T] preserves candidate types through composition |
| Database translators | One spec → SQL, MongoDB, Django Q, SQLAlchemy, Polars, or Pandas expression |
| Serializable | to_dict() / from_dict() — store rules in JSON configs or databases |
| Debuggable | explain() prints a PASS / FAIL tree for every node |
Filtering collections
passed = list(eligible.filter(products)) # lazy generator
failed = list(eligible.reject(products)) # inverse
passed, failed = eligible.partition(products)
count = eligible.count(products)
Debugging
from zspec import explain
print(explain(eligible, product))
# AND FAIL
# ├── InStock PASS
# └── price >= 100 FAIL
Serialization
from zspec import to_dict, from_dict
# Save
json.dump(to_dict(InStock() & MinPrice(100)), f)
# Load — specs are auto-discovered
spec = from_dict(json.load(f))
Store custom rule state in __slots__ whose names match constructor arguments.
Values must be JSON-native: unsupported values such as tuples and callable
predicates raise TypeError instead of changing meaning when saved.
If multiple rule classes share a name, pass an explicit registry to
from_dict() to resolve it; ambiguous names raise TypeError.
Translators
One spec — query any backend:
Built-in translators handle true() and false() automatically, including
constants left by empty factories or dynamic composition. Custom _translate
methods only need to handle domain rules.
# SQL
MySql().translate(eligible) # SqlFragment("((in_stock = %s) AND (price >= %s))", (True, 100))
# MongoDB
MyMongo().translate(eligible) # {"$and": [{...}, {...}]}
# Django
MyDjango().translate(eligible) # Q(price__gte=100) & Q(in_stock=True)
# SQLAlchemy
MySA().translate(eligible) # ColumnElement[bool]
# Polars
MyPolars().translate(eligible) # pl.Expr
# Pandas
MyPandas().translate(eligible) # query string
License
MIT
Metadata
Release files for zspec 1.8.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| zspec-1.8.4.tar.gz | 15.3 kB | Without provenance | Details for zspec-1.8.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| zspec-1.8.4-py3-none-any.whl | Python 3 | none | any | Details for zspec-1.8.4-py3-none-any.whl |
Total release size: 36.4 kB
Release files / zspec-1.8.4.tar.gz
| Download URL | zspec-1.8.4.tar.gz |
|---|---|
| Size | 15.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c9aca44d82589ac18c5ef15f8250d1152f44e09e167b0ab428e097c4dd3df6cc
|
|
BLAKE2b-256 checksum How to use checksums |
24bec4fdae79682baac9d806ea54402e8d322eb1d1fe3d469b26b71231566752
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / zspec-1.8.4-py3-none-any.whl
| Download URL | zspec-1.8.4-py3-none-any.whl |
|---|---|
| Size | 21.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c0ddfe7de4694a62e883e426f067d83569a4d505d00f3b9636d7225e00db86af
|
|
BLAKE2b-256 checksum How to use checksums |
74842925562b4d297f4d6ff3cfe04313c06546474d91fe0ee05a63c5dd8d87d3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.13 {"installer":{"name":"uv","version":"0.12.13","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for zspec 1.8.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.