Composable specification pattern for Python
Project description
zspec
Composable specification pattern for Python 3.14+.
The problem
Business rules tend to spread across your codebase. A check like "is this order eligible for free shipping?" might live in a service method, duplicated in a view, slightly different in a validation layer. When requirements change, you hunt down every copy and hope you found them all.
The Specification pattern solves this by turning each rule into a single, testable object. Combine them with &, |, ^, ~ to express complex logic without writing new classes.
Installation
pip install zspec
Quick start
from dataclasses import dataclass
from zspec import Specification
@dataclass
class Product:
name: str
price: int
in_stock: bool
# Define specifications as simple subclasses
class InStock(Specification[Product]):
def is_satisfied_by(self, p: Product) -> bool:
return p.in_stock
class Affordable(Specification[Product]):
def __init__(self, max_price: int) -> None:
self.max_price = max_price
def is_satisfied_by(self, p: Product) -> bool:
return p.price <= self.max_price
# Compose with &, |, ~
in_stock = InStock()
reasonable = Affordable(max_price=1000)
eligible = in_stock & reasonable
product = Product(name="Laptop", price=800, in_stock=True)
assert eligible(product) # True -- callable directly
assert eligible.is_satisfied_by(product) # same thing
Features
- Composable --- combine specs with
&(and),|(or),^(xor),~(not) - Type-safe --- generic
Specification[T]preserves the candidate type - Bulk combinators ---
Specification.all_of(...)andSpecification.any_of(...) - Zero dependencies --- standard library only
API overview
spec & other— Both must be satisfied (AND)spec | other— At least one must be satisfied (OR)spec ^ other— Exactly one must be satisfied (XOR)~spec— Negation (NOT)spec(candidate)— Shorthand foris_satisfied_bySpecification.of(fn)— Create a spec from a callableSpecification.true()/Specification.false()— Always / never satisfiedspec.filter(iterable)— Lazy filter over a collectionspec.reject(iterable)— Inverse of filterspec.partition(iterable)— Split into(passed, failed)listsSpecification.all_of(specs, default=None)— AND over iterable, returns default when emptySpecification.any_of(specs, default=None)— OR over iterable, returns default when emptyexplain(spec, candidate)— Debug tree showing what passed/failed
Translators
Convert specification trees to SQL, MongoDB filters, Django Q objects, or custom formats:
from dataclasses import dataclass
from zspec import SqlTranslator, SqlFragment, Specification
@dataclass
class Product:
price: int
in_stock: bool
class MinPrice(Specification[Product]):
def __init__(self, price: int) -> None:
self.price = price
def is_satisfied_by(self, candidate: Product) -> bool:
return candidate.price >= self.price
class MySql(SqlTranslator):
def _translate(self, spec: Specification[Product]) -> SqlFragment:
match spec:
case MinPrice(price=price):
return SqlFragment("price >= %s", (price,))
case _:
return super()._translate(spec)
spec = MinPrice(100) & MinPrice(200)
fragment = MySql().translate(spec)
assert fragment.sql == "(price >= %s AND price >= %s)"
assert fragment.params == (100, 200)
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file zspec-1.1.0.tar.gz.
File metadata
- Download URL: zspec-1.1.0.tar.gz
- Upload date:
- Size: 6.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.11.16 {"installer":{"name":"uv","version":"0.11.16","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}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5a3129e2c62c91617a3566cc17e29f98cbc65318a26c8975355a6c61f4a6fd02
|
|
| MD5 |
5a26e68334e41ed008dd26bccf988bac
|
|
| BLAKE2b-256 |
4c968534136393328b16ec93b98278f941c5c46fdc6df78dab89eac31545aede
|
File details
Details for the file zspec-1.1.0-py3-none-any.whl.
File metadata
- Download URL: zspec-1.1.0-py3-none-any.whl
- Upload date:
- Size: 9.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.11.16 {"installer":{"name":"uv","version":"0.11.16","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}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fe6d192f59aa1014b9862a189360f52da045e081ba81d10a9fb07b5fa515bed0
|
|
| MD5 |
607cba6099e1a7cbe5202176ef8377d6
|
|
| BLAKE2b-256 |
64cd5f9b8e03097a3623e410e15bbe7a1291fdea46452b15696477b926238e7f
|