Skip to main content

Design-by-contract library for Python, implemented in Rust.

Project description

contract-check

Sponsor

This is a design-by-contract library for Python, implemented in Rust.

contract-check は、Python 向けの契約プログラミングライブラリです。公開 API は Python の decorator 中心で設計し、内部の構造化違反情報と実行時基盤を Rust で実装します。 思想面では life4/deal を参考にしつつ、配布、監査性、 AI 補助開発、Python/Rust 混成運用を前提に再設計しています。

クイックスタート

pip install contract-check

PyPI wheel 配布対象:

  • macOS
  • Linux
  • Windows

macOS wheel は universal2 を使い、Apple Silicon と Intel の両方を対象にします。

import asyncio

from python_contracts_rs import (
    ContractViolationError,
    contract,
    invariant,
    invariant_class,
    post,
    pre,
    pure,
    raises,
)


def divisor_is_not_zero(divisor: int) -> bool:
    return divisor != 0


def quotient_matches_dividend(result: int, dividend: int, divisor: int) -> bool:
    return result * divisor == dividend


def value_is_positive(value: int) -> bool:
    return value > 0


def result_is_incremented(result: int, value: int) -> bool:
    return result == value + 1


def balance_is_non_negative(self: "Wallet") -> bool:
    return self.balance >= 0


@contract(
    pre(divisor_is_not_zero),
    post(quotient_matches_dividend),
    raises(ZeroDivisionError),
    pure(),
)
def divide(dividend: int, divisor: int) -> int:
    if divisor == 0:
        raise ZeroDivisionError("division by zero")
    return dividend // divisor


@contract(
    pre(value_is_positive),
    post(result_is_incremented),
)
async def async_increment(value: int) -> int:
    await asyncio.sleep(0)
    return value + 1


@invariant_class(
    invariant(balance_is_non_negative),
)
class Wallet:
    def __init__(self, balance: int) -> None:
        self.balance = balance

    def debit(self, amount: int) -> None:
        self.balance -= amount


assert divide(12, 3) == 4
assert asyncio.run(async_increment(2)) == 3

配布名と import 名:

  • PyPI distribution 名は contract-check です
  • Python import 名は現時点では python_contracts_rs です

標準挙動:

  • 契約は sync / async 関数の両方で有効です
  • PYTHON_CONTRACTS_RS=0 で実行時に無効化できます
  • 契約違反は ContractViolationError として送出され、to_dict() / to_json() で構造化出力できます
  • pre(...) / post(...) / invariant(...) / error(...) は callable を受け取り、手書きの条件文字列は受け取りません
  • condition には callable 名または例外型名のような導出ラベルが入ります

提供機能

機能 Python API 補足
前提条件 pre(...) sync / async / async generator の実行前に検証
事後条件 post(...) 戻り値は result / ret で参照
不変条件 invariant(...) / @invariant_class(...) method 単位または class 全体へ注入
期待例外 raises(...) / error(...) 許可された例外のみ通過
純粋性 pure(...) 現段階では意図表明
panic 方針 panic_free(...) 予期しない例外を契約違反へ変換
契約メタデータ get_contract_metadata(...) ドキュメント生成やテスト補助向け
構造化出力 violation_to_dict(...) / violation_to_json(...) CI や監査ログ向け
SARIF 出力 violation_to_sarif_result(...) / violations_to_sarif(...) GitHub code scanning 連携向け

詳細は docs/contracts.md を参照してください。

リポジトリ構成

  • python/python_contracts_rs/ Python 公開 API と decorator 実装です。
  • bindings/python-contracts-rs/ PyO3 ベースの Python/Rust バインディングです。
  • crates/rust-contract-checks/ Rust 側の低レベルな契約種別・違反情報・設定判定です。
  • examples/quickstart.py Python 利用者向けの最短例です。
  • tests/python/test_contracts.py Python 公開 API の統合テストです。
  • tests/contracts.rs Rust コアの回帰テストです。

生成 AI 向け案内

このプロジェクトは Python library implemented in Rust です。Rust 単独ライブラリとして 読まないでください。読む順序は次を推奨します。

  1. この README.md
  2. docs/contracts.md
  3. examples/quickstart.py
  4. tests/python/test_contracts.py
  5. ARCHITECTURE.md
  6. AGENTS.md

AI 運用方針:

  • 主成果物は Python API として扱う
  • 内部推論を英語で行う運用は許容
  • 最終回答とコードコメントは日本語
  • 仕様変更時は README / examples / tests / docs を同時更新

開発

ローカル開発:

make setup
make ci

Docker:

docker build -t contract-check .
docker run --rm -it -v "$PWD:/workspace" contract-check make ci

Dev Container は .devcontainer/devcontainer.json を参照してください。

現状の制限

  • @invariant_class(...) は public instance method と __init__ を対象にします
  • private / dunder / staticmethod / classmethod への自動適用は明示設定または将来拡張の対象です
  • pure(...) は意図表明です
  • tracing backend は未実装です

ライセンス

MIT License。詳細は LICENSE を参照してください。

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

contract_check-0.3.7.tar.gz (31.5 kB view details)

Uploaded Source

Built Distributions

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

contract_check-0.3.7-cp39-abi3-win_amd64.whl (160.6 kB view details)

Uploaded CPython 3.9+Windows x86-64

contract_check-0.3.7-cp39-abi3-manylinux_2_34_x86_64.whl (311.6 kB view details)

Uploaded CPython 3.9+manylinux: glibc 2.34+ x86-64

contract_check-0.3.7-cp39-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl (528.1 kB view details)

Uploaded CPython 3.9+macOS 10.12+ universal2 (ARM64, x86-64)macOS 10.12+ x86-64macOS 11.0+ ARM64

File details

Details for the file contract_check-0.3.7.tar.gz.

File metadata

  • Download URL: contract_check-0.3.7.tar.gz
  • Upload date:
  • Size: 31.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for contract_check-0.3.7.tar.gz
Algorithm Hash digest
SHA256 910174611712e0793697d267aa16ea9968b158d17d0654101ffcb56c8c7e6599
MD5 25c98a9e772cd5efdf0e15839e31307a
BLAKE2b-256 addf21f64ff0b8e173532561f0bc72e76302c0551d0c1a3b1f751c871bcce9fb

See more details on using hashes here.

File details

Details for the file contract_check-0.3.7-cp39-abi3-win_amd64.whl.

File metadata

File hashes

Hashes for contract_check-0.3.7-cp39-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 ae0a621e33ba866a9f87c3fee12d18cc31a49bed6846bfa9468255292dcb4dd5
MD5 599be10b59ec2a66a26a3701c4b38d76
BLAKE2b-256 79c40205083091d21d616e3db3ffd9b9d825c24f3f994cfa69937a0c9e330b10

See more details on using hashes here.

File details

Details for the file contract_check-0.3.7-cp39-abi3-manylinux_2_34_x86_64.whl.

File metadata

File hashes

Hashes for contract_check-0.3.7-cp39-abi3-manylinux_2_34_x86_64.whl
Algorithm Hash digest
SHA256 ea86f9fdf2329faf7e00415036b74f4e8192065aa0698220db27e6da859e2115
MD5 3886a3069454e7264a863227457cf533
BLAKE2b-256 0c49dba39d3f21303c8f97daea3001dd5932a7c61e626a93ed49b3307a5bc330

See more details on using hashes here.

File details

Details for the file contract_check-0.3.7-cp39-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl.

File metadata

File hashes

Hashes for contract_check-0.3.7-cp39-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl
Algorithm Hash digest
SHA256 fceef529e3b808a5d5e61d2fee2241d2012e2dfa60db5d35cec063bfa1a3e73b
MD5 3817e4db3a2e4f5257543e5581539c14
BLAKE2b-256 40c7f1faac5a348c67fcf2afeff5ac626e723ccc6257066a5a6faa29f05f63f0

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