Skip to main content

zspec

PyPI Python CI Docs License

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.

Translators

One spec — query any backend:

# 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.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for zspec 1.8.3
File Size Uploaded Provenance Actions
zspec-1.8.3.tar.gz 14.0 kB Without provenance Details for zspec-1.8.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for zspec 1.8.3
File Interpreter ABI Platform Actions
zspec-1.8.3-py3-none-any.whl Python 3 none any Details for zspec-1.8.3-py3-none-any.whl

Total release size: 33.8 kB

Release files / zspec-1.8.3.tar.gz

Download URL zspec-1.8.3.tar.gz
Size 14.0 kB
Tags Source
SHA-256 checksum
How to use checksums
1a978eadca679ad68c8997b711f2bcd572a635e7407662594ffe391bff04389d
BLAKE2b-256 checksum
How to use checksums
be45aef63c6c1e1db2c0e39fd9502f6dca71dabc4a1d01f02343d82b5d4f2ad7
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.3-py3-none-any.whl

Download URL zspec-1.8.3-py3-none-any.whl
Size 19.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
990faefd033887a525f7ec267d9e039992dacc6fb6a12463addf2b3675c9f4db
BLAKE2b-256 checksum
How to use checksums
57321737323e711370459c01059c52f34666de19b7ad6a95c01b4094b46bb643
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.3

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page