Skip to main content

Composable specification pattern for Python

Project description

zspec

PyPI Python CI Coverage License

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 combinatorsSpecification.all_of(...) and Specification.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 for is_satisfied_by
  • Specification.of(fn) — Create a spec from a callable
  • Specification.true() / Specification.false() — Always / never satisfied
  • spec.filter(iterable) — Lazy filter over a collection
  • spec.reject(iterable) — Inverse of filter
  • spec.partition(iterable) — Split into (passed, failed) lists
  • Specification.all_of(specs, default=None) — AND over iterable, returns default when empty
  • Specification.any_of(specs, default=None) — OR over iterable, returns default when empty
  • explain(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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

zspec-1.2.1.tar.gz (7.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

zspec-1.2.1-py3-none-any.whl (9.9 kB view details)

Uploaded Python 3

File details

Details for the file zspec-1.2.1.tar.gz.

File metadata

  • Download URL: zspec-1.2.1.tar.gz
  • Upload date:
  • Size: 7.2 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

Hashes for zspec-1.2.1.tar.gz
Algorithm Hash digest
SHA256 c50df936959b44c88e2c1a818f7b6e47493dd6297c570e7535b4b65feefaacdb
MD5 f24103c1ce7fb575a3cbbb8d7f849270
BLAKE2b-256 eb5a341ef270b179b460b7ecf2d6ad40b66dcdd8d0e63f34c15894b363768b69

See more details on using hashes here.

File details

Details for the file zspec-1.2.1-py3-none-any.whl.

File metadata

  • Download URL: zspec-1.2.1-py3-none-any.whl
  • Upload date:
  • Size: 9.9 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

Hashes for zspec-1.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b572fa431aa3f01342a870e205d3b3f55faf07121c0af223e95db33284c306e8
MD5 d1eaf2eb0ea59bb7391aa3a14b941b15
BLAKE2b-256 442e31a761f3871080eb32cd28b6dae36abec14e4388e9b97caceecc8e536a59

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page