Skip to main content

Composable specification pattern for Python

Project description

ZSpec

PyPI Python 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 combinators --- Specification.all_of(...) and Specification.any_of(...)
  • Zero dependencies --- standard library only
  • Python 3.14+ --- leverages modern generics (class Foo[T])

API overview

Method Description
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
spec.filter(iterable) Lazy filter over a collection
Specification.all_of(specs) Reduce with AND, returns None for empty input
Specification.any_of(specs) Reduce with OR, returns None for empty input
explain(spec, candidate) Debug tree showing what passed/failed

Translators

Convert specification trees to SQL, MongoDB filters, Django Q objects, or custom formats:

from zspec import SqlTranslator, SqlFragment, Specification


class MinPrice(Specification[Any]):
    def __init__(self, price: int) -> None:
        self.price = price

    def is_satisfied_by(self, candidate: object) -> bool:
        return True  # evaluated in DB


class MySql(SqlTranslator):
    def _translate(self, spec: Specification[Any]) -> SqlFragment:
        match spec:
            case MinPrice(price=price):
                return SqlFragment("price >= %s", (price,))
            case _:
                raise NotImplementedError


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-0.1.1.tar.gz (6.4 kB view details)

Uploaded Source

Built Distribution

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

zspec-0.1.1-py3-none-any.whl (9.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: zspec-0.1.1.tar.gz
  • Upload date:
  • Size: 6.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.11 {"installer":{"name":"uv","version":"0.11.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Fedora Linux","version":"43","id":"","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for zspec-0.1.1.tar.gz
Algorithm Hash digest
SHA256 09dd17d806aa75b128aa099c4289ee80d4e22e6cebaa2f25171a95b05cfe7c8e
MD5 590bf59a707c38096576074a0d047789
BLAKE2b-256 2fd01721b2c02a2d1e7995eea7baddd73074a9e9d3162963c409d34ca7402b4f

See more details on using hashes here.

File details

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

File metadata

  • Download URL: zspec-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 9.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.11 {"installer":{"name":"uv","version":"0.11.11","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Fedora Linux","version":"43","id":"","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for zspec-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 55a76032cf8a21e94d960215d135f75629469dcb0b462977629529c6a70a131c
MD5 71d553f482b4db85356300ee09ec782b
BLAKE2b-256 43c7feb72eeb499084ddac6ba37d8891959d1c5d207e8f8b28d6061f11655dbb

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