type_enforced

type_enforced

PyPI version Python Version License: MIT DOI PyPI Downloads

Fast where it counts, thorough where it matters. Runtime validation for Python type annotations. Zero dependencies and uncompromising performance.

type_enforced logo


Table of Contents


Quick Start

import type_enforced

# 1. Complete validation
@type_enforced.Enforcer
def greet(name: list[str], repeat: int = 1) -> str:
    return f"Hello {', '.join(name)}!" * repeat

greet(["Alice"], 2)       # Returns "Hello Alice!Hello Alice!"
greet(["Alice"], "twice")  # Raises TypeError at runtime!

# 2. Fast O(1) validation (does not check every item in passed collections)
@type_enforced.FastEnforcer
def process_tags(tags: list[str]) -> int:
    return len(tags)

process_tags(["admin", "user"])  # Returns 2
process_tags([123, "user"])       # Raises TypeError (first element is checked)

Enforce an entire module (complete or fast O(1) sampled validation):

import my_package
import type_enforced

# Enforce all functions and classes across my_package
type_enforced.ModuleEnforcer(my_package)

# Or for fast O(1) sampled validation across my_package:
# type_enforced.FastModuleEnforcer(my_package)

Why type_enforced?

Static type checkers (like mypy or pyright) catch errors during development, but offer zero protection at runtime against dynamic payloads, untyped API inputs, or user data.

Existing runtime type checkers force an unnecessary compromise:

  • Pydantic provides thorough validation, but comes with heavy runtime overhead and steep execution slowdowns.
  • Beartype achieves high speed primarily by taking shortcuts. It samples 1 element in collections and misses invalid items in unsampled data.

type_enforced eliminates this compromise:

  • Guaranteed Complete Validation: Validates every single item across large collections and nested data structures (e.g. list[dict[str, int]] or dicts with 10,000+ keys) by default, with zero shortcuts.
  • Fastest Full Validation: Delivers full, uncompromising validation at a fraction of other packages' overhead.
  • Fastest Sampled Validation: Need O(1) or logarithmic sampling for massive collections? This is how Beartype works. Set iterable_sample_pct='first', 'last', 'bookend', 'bookend_plus', 'log', 0 (random pick), or a percentage. Sampled validation in type_enforced runs up to ~15x faster than Beartype.
  • Zero Dependencies & Pure Python Compatible: Zero external runtime dependencies. Runs everywhere standard Python 3.11+ runs, with optional automatic C++ acceleration via nanobind when available.
  • Rich Type Support & Constraints: Seamlessly supports standard Python | unions, nested generics, Literals, Callables, Dataclasses, custom class inheritance, and custom validation Constraint rules.
  • Clean Tracebacks: Strips internal validation frames from tracebacks by default, pinpointing the exact line in your code that caused the issue.

Performance at a Glance

Timings represent the added differential validation time (enforced call time minus non-enforced baseline call time) in nanoseconds (ns), averaged over 100 runs when using the C++ backend. For full benchmarks see utils/benchmark.py and benchmark.md.

Type Size type_enforced (sample=1) Beartype (sample=1) Typeguard (sample=1) type_enforced (100%) Pydantic (100%) msgspec (100%) cattrs (100%) Typeguard (100%)
int — 10.6 ns 194.4 ns 1843.0 ns 10.5 ns 446.0 ns 291.2 ns 114.6 ns 1846.8 ns
Union[int, float] — 16.1 ns 211.3 ns 3874.8 ns 16.2 ns 503.0 ns 437.4 ns 425.9 ns 3899.4 ns
str — 10.9 ns 196.0 ns 1868.1 ns 10.5 ns 440.6 ns 287.7 ns 119.3 ns 1865.4 ns
list[int] 1 000 items 27.6 ns 334.8 ns 3167.6 ns 462.4 ns 10991.3 ns 5067.3 ns 47633.3 ns 1044342.6 ns
dict[str, int] 1 000 keys 27.6 ns 340.4 ns 4447.4 ns 3087.4 ns 39815.9 ns 26384.5 ns 67925.4 ns 2044397.2 ns
list[list[int]] 10 x 100 items 25.2 ns 371.7 ns 4425.3 ns 374.9 ns 11485.1 ns 5893.3 ns 48306.4 ns 1044535.2 ns
dict[str, list[int]] 10 x 100 items 32.3 ns 448.3 ns 5731.4 ns 408.0 ns 11898.6 ns 6348.2 ns 48556.2 ns 1060810.2 ns
list[dict[str, int]] 10 x 100 items 33.4 ns 441.7 ns 5696.3 ns 3230.0 ns 38542.1 ns 25667.0 ns 66924.7 ns 2071112.0 ns

Sampled Validation: When 1 sample validation is acceptable, type_enforced.FastEnforcer is up to ~15x faster than Beartype.

Full Validation: When full validation is required, type_enforced.Enforcer is up to ~40x faster than Pydantic on scalars and up to ~20x faster on larger data structures.


Installation

Install via pip:

pip install type_enforced

Or using uv:

uv add type_enforced

Requirements & Build Options

  • Python 3.11+
  • Zero Runtime Dependencies: Self-contained package with zero external runtime dependencies.
  • Pre-Built Binary Wheels: Pre-compiled wheels with C++ acceleration are published on PyPI for standard platforms (Linux, macOS, Windows).
  • Source Build & Automatic Fallback: If installing from source (pip install . or pip install --no-binary type_enforced type_enforced), type_enforced attempts to compile C++ extension modules via nanobind. If a C++ compiler is not present or compilation fails, it automatically falls back to pure-Python mode without failing the installation.
  • Force Pure-Python Mode (Skip C++ Build): To explicitly skip C++ compilation and install in pure-Python mode:

    Expand to show details on how to force pure-Python mode

    Environment Variable (CLI or CI):

    TYPE_ENFORCED_NO_BUILD=1 pip install type_enforced --no-binary type_enforced
    

    pip CLI (PEP 517 Config Setting):

    pip install type_enforced --no-binary type_enforced -Cwheel.cmake=false
    

    uv (in pyproject.toml):

    [tool.uv]
    no-binary-package = ["type-enforced"]
    config-settings-package = { type-enforced = { "wheel.cmake" = "false" } }
    

    pip (in requirements.txt):

    type_enforced --no-binary type_enforced --config-settings=wheel.cmake=false
    
    • Verify C++ Acceleration Status: Check whether C++ acceleration is active in the current environment:
    import type_enforced
    
    print(type_enforced.has_cpp())  # True if C++ acceleration is active, False for pure Python
    

Legacy Python Compatibility For older Python versions, pin to legacy releases: - **Python 3.10**: `pip install "type_enforced<=1.10.2"` - **Python 3.9**: `pip install "type_enforced<=1.9.0"` - **Python 3.7 – 3.8**: `pip install "type_enforced==0.0.16"`

Usage Guide

1. Functions and Methods

Apply `@type_enforced.Enforcer` or `@type_enforced.FastEnforcer` to any callable. It validates positional arguments, keyword arguments, default parameters, and the return type.
import type_enforced

@type_enforced.Enforcer
def process_user(user_id: int, tags: list[str], active: bool = True) -> dict[str, str | int]:
    return {"user_id": user_id, "status": "active" if active else "inactive"}

# Passing invalid types raises a descriptive TypeError:
process_user("123", ["admin"])
# TypeError: TypeEnforced Exception (process_user): Type mismatch for typed variable `user_id`.
# Expected one of the following `[<class 'int'>]` but got `<class 'str'>` with value `123` instead.

2. Classes and Dataclasses

Decorating a class with `@type_enforced.Enforcer` or `@type_enforced.FastEnforcer` automatically enforces types on all annotated methods (including `__init__`, `@classmethod`, and `@staticmethod`):
import type_enforced
from dataclasses import dataclass

@type_enforced.Enforcer
class Account:
    def __init__(self, username: str, balance: float):
        self.username = username
        self.balance = balance

    def deposit(self, amount: float) -> float:
        self.balance += amount
        return self.balance

    @staticmethod
    def validate_code(code: str) -> bool:
        return len(code) == 6

# Dataclasses work seamlessly:
@type_enforced.Enforcer
@dataclass
class UserConfig:
    retries: int
    endpoint: str
To disable enforcement on a specific method within an enforced class:
@type_enforced.Enforcer
class Worker:
    def standard_job(self, task: str) -> None:
        pass

    @type_enforced.Enforcer(enabled=False)
    def high_throughput_job(self, data):
        # Type enforcement skipped for maximum throughput
        pass

3. Module-Level Enforcement (ModuleEnforcer or FastModuleEnforcer)

Enforce typing across an entire module in a single line without decorating every function and class individually:
# Place at the top of your module file (e.g., my_package/core.py)
import type_enforced

type_enforced.ModuleEnforcer()      # Complete validation across module
# Or for fast O(1) sampled validation across the module:
# type_enforced.FastModuleEnforcer()

def add(a: int, b: int) -> int:
    return a + b

class Helper:
    def run(self, flag: bool) -> str:
        return "ok" if flag else "failed"
You can also enforce an imported module:
import my_package
import type_enforced

type_enforced.ModuleEnforcer(my_package)
# Or: type_enforced.FastModuleEnforcer(my_package)

Note: By default, submodules=True, which recursively enforces all sub-packages/sub-modules in the same namespace (e.g. mypkg.submodule), while safely ignoring third-party and standard library imports.


Supported Type Annotations

type_enforced supports all standard Python 3.11+ typing constructs:

Standard Built-ins & Unions

@type_enforced.Enforcer
def fn(
    a: int,
    b: str | float,                    # Standard union syntax
    c: int | None = None,              # Optional syntax
) -> None:
    pass

Collections & Nested Generics

@type_enforced.Enforcer
def fn(
    items: list[int | float],
    mapping: dict[str, list[int]],      # Dicts require [KeyType, ValType]
    unique_ids: set[str],
    fixed_pair: tuple[str, int],        # Exact positional tuple: (str, int)
    var_tuple: tuple[int, ...],         # Variable-length tuple
) -> None:
    pass

Custom Classes & Subclass Inheritance

By default, subclasses pass type validation (e.g. Bar() satisfies Foo if class Bar(Foo)):

class Animal: pass
class Dog(Animal): pass
class Vehicle: pass

@type_enforced.Enforcer
def feed(animal: Animal) -> None:
    pass

feed(Animal())  # OK
feed(Dog())     # OK (subclasses allowed)
feed(Vehicle()) # Raises TypeError

To enforce uninitialized class objects (the class itself, rather than an instance), use type[Animal] (or typing.Type[Animal]):

@type_enforced.Enforcer
def make_instance(cls: type[Animal]) -> Animal:
    return cls()

Literals & Special Types

from typing import Literal, Callable, Sized, Any

@type_enforced.Enforcer
def fn(
    mode: Literal["read", "write"],        # Value check: must equal "read" or "write"
    handler: Callable,                     # Functions, methods, generators
    container: Sized,                      # list, dict, set, str, tuple, bytes, etc.
    wildcard: Any,                         # Permissive bypass
) -> None:
    pass
  • Stacking Literals: Literals combine with unions using OR logic (int | Literal['auto'] allows any int or the literal string 'auto').

Modern Typing Constructs (PEP Standards)

type_enforced comprehensively supports modern typing features from recent Python PEPs:

from typing import (
    Callable,
    LiteralString,
    Never,
    NewType,
    NoReturn,
    Self,
    TypeGuard,
    TypeIs,
    TypeVar,
    TypedDict,
)

# 1. PEP 673: typing.Self
class Builder:
    @type_enforced.Enforcer
    def set_name(self, name: str) -> Self:
        self.name = name
        return self

# 2. PEP 589: typing.TypedDict (validates required keys & field types)
class UserPayload(TypedDict):
    id: int
    name: str

@type_enforced.Enforcer
def create_user(payload: UserPayload) -> str:
    return payload["name"]

# 3. PEP 484: typing.NewType
UserId = NewType("UserId", int)

@type_enforced.Enforcer
def get_user(user_id: UserId) -> None:
    pass

# 4. Subscripted Callables (PEP 484 & PEP 612)
@type_enforced.Enforcer
def apply_handler(callback: Callable[[int, str], bool]) -> None:
    pass

# 5. PEP 675: typing.LiteralString
@type_enforced.Enforcer
def run_query(sql: LiteralString) -> None:
    pass

# 6. PEP 484 / PEP 654: NoReturn and Never
@type_enforced.Enforcer
def terminate() -> NoReturn:
    raise SystemExit(0)

# 7. PEP 647 & PEP 742: TypeGuard and TypeIs
@type_enforced.Enforcer
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in val)

# 8. TypeVar, ParamSpec, TypeVarTuple & PEP 695 (Python 3.12+)
T = TypeVar("T", bound=int | float)

@type_enforced.Enforcer
def scale(val: T, factor: float) -> float:
    return val * factor

Collection & Nested Type Unions

Unions of collection types are evaluated per-variant, enforcing that each container strictly satisfies one schema rather than allowing mixed elements:

@type_enforced.Enforcer
def process_data(
    coords: tuple[int, str] | tuple[str, int],
    lookup: dict[str, list[int]] | dict[str, int],
    tags: list[int] | list[str],
) -> None:
    pass

# Distinct collection schemas match:
process_data((1, "north"), {"a": [1, 2]}, [1, 2, 3])  # OK
process_data(("north", 1), {"a": 10}, ["a", "b"])  # OK

# Mixed invalid structures fail:
process_data((1, 1), {"a": 10}, [1, 2])  # Raises TypeError for coords
process_data(
    (1, "north"), {"a": 1, "b": [2]}, [1, 2]
)  # Raises TypeError for lookup
process_data((1, "north"), {"a": 10}, [1, "two"])  # Raises TypeError for tags

Variadic Positional & Keyword Arguments

*args and **kwargs are fully supported with clear, indexed error messages:

@type_enforced.Enforcer
def configure(*flags: str, **settings: int | bool) -> None:
    pass

configure("verbose", "debug", timeout=30, dry_run=True)  # OK
configure("verbose", 123)  # Raises TypeError: Type mismatch for typed variable `flags[1]`
configure(timeout="30s")   # Raises TypeError: Type mismatch for typed variable `settings['timeout']`

Known Limitations / Currently Unsupported

  • Generic parameterization of Sized (e.g. Sized[int] — use Sized without inner type arguments)

Value Validation with Constraints

type_enforced allows post-type-check value constraints directly in type annotations.

Built-in Constraint

Validate bounds, numeric comparisons, string patterns (regex), and inclusion/exclusion:

import type_enforced
from type_enforced.utils import Constraint

@type_enforced.Enforcer
def set_score(
    score: int | Constraint(ge=0, le=100),
    code: str | Constraint(pattern=r"^[A-Z]{3}[0-9]{4}$"),
) -> bool:
    return True

set_score(85, "ABC1234")    # Passes
set_score(105, "ABC1234")   # Raises TypeError (Constraint `Less Than Or Equal To (100)` not met)
set_score(85, "invalid")    # Raises TypeError (Constraint `Regex Pattern Match` not met)

Available Constraint parameters:

  • gt, lt, ge, le, eq, ne (numeric / comparison bounds)
  • pattern (regular expression string match)
  • includes, excludes (membership checks)

Custom GenericConstraint

Write arbitrary validation logic using custom predicates:

import type_enforced
from type_enforced.utils import GenericConstraint

RGBColor = str | GenericConstraint({
    "valid_hex_color": lambda c: c.startswith("#") and len(c) in (4, 7)
})

@type_enforced.Enforcer
def render(color: RGBColor) -> None:
    pass

render("#ffffff")  # Passes
render("red")      # Raises TypeError (Constraint `valid_hex_color` not met)

Note: Constraints are evaluated after type checking. Constraints stack with unions: int | Constraint(ge=0) | Constraint(le=10).


Configuration Reference

@Enforcer, @FastEnforcer, ModuleEnforcer, and FastModuleEnforcer accept the following configuration arguments:

Parameter Type Default Description
enabled bool True Toggle enforcement. Set False to bypass type checks (useful for production vs. debugging or per-method overrides).
strict bool True When True, raises TypeError on mismatch. When False, logs a warning to the console instead of raising.
clean_traceback bool True Filters internal type_enforced stack frames so unhandled tracebacks point directly to user code (see note below).
iterable_sample_pct int, float, or str 100 ('first' for Fast*) Sampling mode or percentage (0–100) of iterable items to validate. 'first' checks the first item, 'last' checks the last item (or first item for dicts/sets), 'bookend' checks first and last items (first 2 items for dicts/sets), 'bookend_plus' checks first, last, and a random middle item (first 2 items and 1 random item for dicts/sets), 'log' checks a sample of ceil(log2(n)) items using a pseudo-random start offset and even steps across sequences (first ceil(log2(n)) items for dicts/sets), 0 checks 1 random item, and 1..100 checks the specified percentage (rounding up) starting at a pseudo-random offset within each step interval for sequences (first $N$ items for dicts/sets). 100 validates all elements. Note: FastEnforcer and FastModuleEnforcer strictly accept 'first', 'last', 'bookend', 'bookend_plus', 'log', or 0.
only_typed bool False When True, raises an exception upon decoration if any parameter or return value lacks a type hint.
submodules (ModuleEnforcers only) bool True Recursively enforces all sub-packages/sub-modules in the same namespace.

Configuration Options in Depth

1. Strict Typing Mode (only_typed=True)

To catch unannotated parameters or missing return annotations across your codebase, enable only_typed=True. This raises a TypeError at definition time if any parameter (excluding self/cls) or the return type lacks an annotation:

import type_enforced

@type_enforced.Enforcer(only_typed=True)
def calculate(a: int, b: int) -> int:
    return a + b

# Missing annotation on parameter `b` or missing return annotation raises immediately:
@type_enforced.Enforcer(only_typed=True)
def invalid_fn(a: int, b):
    return a
# TypeError: TypeEnforced Exception (invalid_fn): Untyped variable `b` found in function/method `invalid_fn`.

2. Warning Mode (strict=False)

Print warnings to the console instead of raising exceptions (useful for gradual adoption or debugging without breaking execution):

@type_enforced.Enforcer(strict=False)
def lenient_fn(x: int) -> int:
    return x

lenient_fn("not_an_int")
# Logs: TypeEnforced Warning (lenient_fn): Type mismatch for typed variable `x`...
# Returns "not_an_int" without raising an exception.

3. Clean Tracebacks (clean_traceback=True)

By default, clean_traceback=True temporarily hooks sys.excepthook when a type exception is raised, stripping internal type_enforced library frames so that unhandled script tracebacks point directly to the line of user code that caused the issue.

Note on Interactive Terminals / REPLs: In interactive environments (such as the Python REPL / PyREPL, IPython, or Jupyter notebooks), the shell wraps execution in an internal try...except loop and catches exceptions before they reach sys.excepthook. Consequently, interactive terminal sessions will still display the full traceback.

4. Sampled Validation (FastEnforcer, FastModuleEnforcer, iterable_sample_pct)

For large or performance-critical collections, use @type_enforced.FastEnforcer or configure sampling instead of full iteration:

  • 'first' (default for FastEnforcer / FastModuleEnforcer): Validates the first element in O(1) time (runs up to ~15x faster than Beartype).
  • 'last': Validates the last element in O(1) time for indexable sequences (list, tuple). For non-indexed collections like dict and set, 'last' validates the first item to avoid reverse iteration and hash table lookup overhead.
  • 'bookend': Validates the first and last elements in O(1) time for sequences (the first 2 items for dict and set).
  • 'bookend_plus': Validates the first, last, and a random middle element in O(1) time for sequences (the first 2 items and 1 random item for dict and set).
  • 'log': For sequences (list, tuple), samples ceil(log2(n)) items by picking a Weyl pseudo-random start offset and taking even step jumps across the collection. For dict and set, validates the first ceil(log2(n)) items.
  • 0: Validates one element chosen at random.
  • 1..99 (int, Enforcer / ModuleEnforcer only): Validates the specified percentage of items (rounding up). For sequences, selects a Weyl pseudo-random start offset in [0, step - 1] and takes even step jumps across the collection, giving every index an equal probability of being checked. For dict and set, validates the first N items.
  • 100: Complete validation of all items across the collection.
# Using FastEnforcer directly:
@type_enforced.FastEnforcer
def fast_check(items: list[int]) -> int:
    return len(items)

fast_check([1, 2, 3])           # OK
fast_check(["bad_first", 2, 3])  # Raises TypeError

# Or configure Enforcer with a specific sample mode:
@type_enforced.Enforcer(iterable_sample_pct="last")
def check_last(items: list[int]) -> int:
    return len(items)

Production Best Practices

Multi-Threaded Services & Web Frameworks (clean_traceback=False)

By default, clean_traceback=True temporarily hooks sys.excepthook to filter internal library frames for standalone scripts. In concurrent multi-threaded environments and applications using centralized error handlers, consider setting clean_traceback=False:

import type_enforced

@type_enforced.Enforcer(clean_traceback=False)
def process_request(user_id: int, tags: list[str]) -> dict:
    return {"user_id": user_id, "tags": tags}

Contributing

Contributions are welcome!

Development Setup

We use uv for dependency management and testing in a Unix-based environment (Linux, macOS, or WSL2 on Windows).

# Clone the repository
git clone https://github.com/connor-makowski/type_enforced.git
cd type_enforced

# Install dev dependencies
uv sync --extra dev

Development Commands

Command Description
uv run pytest Run tests in local environment
uv run pytest -v Run tests with verbose output
uv run nox Run test suite across Python 3.11–3.14 (C++ and pure-Python fallback)
uv run nox -s tests-3.14 Run test suite on a specific Python version
uv run python utils/minibench.py Run quick performance at a glance benchmark
uv run python utils/cpp_vs_python_bench.py Run C++ accelerated vs pure Python benchmark
uv run python utils/prettify.py Auto-format with autoflake and black (80 col)

Guidelines

  1. Fork the repo and create your branch from main.
  2. Ensure all tests pass across versions (uv run nox).
  3. Format code before committing (uv run python utils/prettify.py).
  4. Keep commits atomic and clearly described.
  5. Submit a pull request.

Academic Citation

If you use type_enforced in academic research, please cite our JOSS paper:

@article{Makowski2026,
  doi = {10.21105/joss.08832},
  url = {https://doi.org/10.21105/joss.08832},
  year = {2026},
  publisher = {The Open Journal},
  volume = {11},
  number = {118},
  pages = {8832},
  author = {Connor Makowski},
  title = {type_enforced: A pure Python runtime type enforcer},
  journal = {Journal of Open Source Software}
}

License

Distributed under the MIT License. See LICENSE for details.

  1"""
  2# type_enforced
  3
  4[![PyPI version](https://img.shields.io/pypi/v/type_enforced.svg?color=blue)](https://pypi.org/project/type_enforced/)
  5[![Python Version](https://img.shields.io/pypi/pyversions/type_enforced.svg)](https://pypi.org/project/type_enforced/)
  6[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
  7[![DOI](https://joss.theoj.org/papers/10.21105/joss.08832/status.svg)](https://doi.org/10.21105/joss.08832)
  8[![PyPI Downloads](https://static.pepy.tech/personalized-badge/type-enforced?period=total&units=INTERNATIONAL_SYSTEM&left_color=GREY&right_color=ORANGE&left_text=Downloads)](https://pepy.tech/projects/type-enforced)
  9
 10Fast where it counts, thorough where it matters. Runtime validation for Python type annotations. Zero dependencies and uncompromising performance.
 11
 12<p align="center">
 13  <img src="https://raw.githubusercontent.com/connor-makowski/type_enforced/refs/heads/main/static/te_logo_circle.svg" alt="type_enforced logo" width="400">
 14</p>
 15
 16---
 17
 18## Table of Contents
 19- [Quick Start](#quick-start)
 20- [Why type_enforced?](#why-type_enforced)
 21  - [Performance at a Glance](#performance-at-a-glance)
 22- [Installation](#installation)
 23  - [Requirements & Build Options](#requirements--build-options)
 24- [Usage Guide](#usage-guide)
 25  - [1. Functions and Methods](#1-functions-and-methods)
 26  - [2. Classes and Dataclasses](#2-classes-and-dataclasses)
 27  - [3. Module-Level Enforcement](#3-module-level-enforcement-moduleenforcer-or-fastmoduleenforcer)
 28- [Supported Type Annotations](#supported-type-annotations)
 29- [Value Validation with Constraints](#value-validation-with-constraints)
 30- [Configuration Reference](#configuration-reference)
 31  - [Configuration Options in Depth](#configuration-options-in-depth)
 32- [Production Best Practices](#production-best-practices)
 33- [Contributing](#contributing)
 34- [Academic Citation](#academic-citation)
 35- [License](#license)
 36
 37---
 38
 39## Quick Start
 40
 41```python
 42import type_enforced
 43
 44# 1. Complete validation
 45@type_enforced.Enforcer
 46def greet(name: list[str], repeat: int = 1) -> str:
 47    return f"Hello {', '.join(name)}!" * repeat
 48
 49greet(["Alice"], 2)       # Returns "Hello Alice!Hello Alice!"
 50greet(["Alice"], "twice")  # Raises TypeError at runtime!
 51
 52# 2. Fast O(1) validation (does not check every item in passed collections)
 53@type_enforced.FastEnforcer
 54def process_tags(tags: list[str]) -> int:
 55    return len(tags)
 56
 57process_tags(["admin", "user"])  # Returns 2
 58process_tags([123, "user"])       # Raises TypeError (first element is checked)
 59```
 60
 61Enforce an entire module (complete or fast O(1) sampled validation):
 62
 63```python
 64import my_package
 65import type_enforced
 66
 67# Enforce all functions and classes across my_package
 68type_enforced.ModuleEnforcer(my_package)
 69
 70# Or for fast O(1) sampled validation across my_package:
 71# type_enforced.FastModuleEnforcer(my_package)
 72```
 73
 74---
 75
 76## Why type_enforced?
 77
 78Static type checkers (like `mypy` or `pyright`) catch errors during development, but offer zero protection at runtime against dynamic payloads, untyped API inputs, or user data.
 79
 80Existing runtime type checkers force an unnecessary compromise:
 81- **Pydantic** provides thorough validation, but comes with heavy runtime overhead and steep execution slowdowns.
 82- **Beartype** achieves high speed primarily by taking shortcuts. It samples 1 element in collections and misses invalid items in unsampled data.
 83
 84`type_enforced` eliminates this compromise:
 85
 86- **Guaranteed Complete Validation**: Validates every single item across large collections and nested data structures (e.g. `list[dict[str, int]]` or dicts with 10,000+ keys) by default, with zero shortcuts.
 87- **Fastest Full Validation**: Delivers full, uncompromising validation at a fraction of other packages' overhead.
 88- **Fastest Sampled Validation**: Need O(1) or logarithmic sampling for massive collections? This is how Beartype works. Set `iterable_sample_pct='first'`, `'last'`, `'bookend'`, `'bookend_plus'`, `'log'`, `0` (random pick), or a percentage. Sampled validation in `type_enforced` runs up to ~15x faster than Beartype.
 89- **Zero Dependencies & Pure Python Compatible**: Zero external runtime dependencies. Runs everywhere standard Python 3.11+ runs, with optional automatic C++ acceleration via nanobind when available.
 90- **Rich Type Support & Constraints**: Seamlessly supports standard Python `|` unions, nested generics, Literals, Callables, Dataclasses, custom class inheritance, and custom validation `Constraint` rules.
 91- **Clean Tracebacks**: Strips internal validation frames from tracebacks by default, pinpointing the exact line in your code that caused the issue.
 92
 93### Performance at a Glance
 94
 95Timings represent the added differential validation time (enforced call time minus non-enforced baseline call time) in nanoseconds (ns), averaged over 100 runs when using the C++ backend. For full benchmarks see [utils/benchmark.py](utils/benchmark.py) and [benchmark.md](benchmark.md).
 96
 97| Type                   |       Size       | type_enforced (sample=1) | Beartype (sample=1) | Typeguard (sample=1) | type_enforced (100%) | Pydantic (100%)  |  msgspec (100%)  |  cattrs (100%)   | Typeguard (100%) |
 98| :--------------------- | :--------------: | :----------------------: | :-----------------: | :------------------: | :------------------: | :--------------: | :--------------: | :--------------: | :--------------: |
 99| `int`                  |        —         |         10.6 ns          |      194.4 ns       |      1843.0 ns       |       10.5 ns        |     446.0 ns     |     291.2 ns     |     114.6 ns     |    1846.8 ns     |
100| `Union[int, float]`    |        —         |         16.1 ns          |      211.3 ns       |      3874.8 ns       |       16.2 ns        |     503.0 ns     |     437.4 ns     |     425.9 ns     |    3899.4 ns     |
101| `str`                  |        —         |         10.9 ns          |      196.0 ns       |      1868.1 ns       |       10.5 ns        |     440.6 ns     |     287.7 ns     |     119.3 ns     |    1865.4 ns     |
102| `list[int]`            |   1 000 items    |         27.6 ns          |      334.8 ns       |      3167.6 ns       |       462.4 ns       |    10991.3 ns    |    5067.3 ns     |    47633.3 ns    |   1044342.6 ns   |
103| `dict[str, int]`       |    1 000 keys    |         27.6 ns          |      340.4 ns       |      4447.4 ns       |      3087.4 ns       |    39815.9 ns    |    26384.5 ns    |    67925.4 ns    |   2044397.2 ns   |
104| `list[list[int]]`      |  10 x 100 items  |         25.2 ns          |      371.7 ns       |      4425.3 ns       |       374.9 ns       |    11485.1 ns    |    5893.3 ns     |    48306.4 ns    |   1044535.2 ns   |
105| `dict[str, list[int]]` |  10 x 100 items  |         32.3 ns          |      448.3 ns       |      5731.4 ns       |       408.0 ns       |    11898.6 ns    |    6348.2 ns     |    48556.2 ns    |   1060810.2 ns   |
106| `list[dict[str, int]]` |  10 x 100 items  |         33.4 ns          |      441.7 ns       |      5696.3 ns       |      3230.0 ns       |    38542.1 ns    |    25667.0 ns    |    66924.7 ns    |   2071112.0 ns   |
107
108> **Sampled Validation:** When 1 sample validation is acceptable, `type_enforced.FastEnforcer` is **up to ~15x faster than Beartype**.
109
110> **Full Validation:** When full validation is required, `type_enforced.Enforcer` is **up to ~40x faster than Pydantic on scalars and up to ~20x faster on larger data structures**.
111
112---
113
114## Installation
115
116Install via `pip`:
117
118```bash
119pip install type_enforced
120```
121
122Or using `uv`:
123
124```bash
125uv add type_enforced
126```
127
128### Requirements & Build Options
129- **Python 3.11+**
130- **Zero Runtime Dependencies**: Self-contained package with zero external runtime dependencies.
131- **Pre-Built Binary Wheels**: Pre-compiled wheels with C++ acceleration are published on PyPI for standard platforms (Linux, macOS, Windows).
132- **Source Build & Automatic Fallback**: If installing from source (`pip install .` or `pip install --no-binary type_enforced type_enforced`), `type_enforced` attempts to compile C++ extension modules via `nanobind`. If a C++ compiler is not present or compilation fails, it automatically falls back to pure-Python mode without failing the installation.
133- **Force Pure-Python Mode (Skip C++ Build)**: To explicitly skip C++ compilation and install in pure-Python mode:
134    <details>
135    <summary>Expand to show details on how to force pure-Python mode</summary>
136
137    **Environment Variable (CLI or CI)**:
138    ```bash
139    TYPE_ENFORCED_NO_BUILD=1 pip install type_enforced --no-binary type_enforced
140    ```
141
142    **`pip` CLI (PEP 517 Config Setting)**:
143    ```bash
144    pip install type_enforced --no-binary type_enforced -Cwheel.cmake=false
145    ```
146
147    **`uv` (in `pyproject.toml`)**:
148    ```toml
149    [tool.uv]
150    no-binary-package = ["type-enforced"]
151    config-settings-package = { type-enforced = { "wheel.cmake" = "false" } }
152    ```
153
154    **`pip` (in `requirements.txt`)**:
155    ```text
156    type_enforced --no-binary type_enforced --config-settings=wheel.cmake=false
157    ```
158
159    - **Verify C++ Acceleration Status**: Check whether C++ acceleration is active in the current environment:
160    ```python
161    import type_enforced
162
163    print(type_enforced.has_cpp())  # True if C++ acceleration is active, False for pure Python
164    ```
165    </details>
166
167<details>
168<summary>Legacy Python Compatibility</summary>
169
170For older Python versions, pin to legacy releases:
171- **Python 3.10**: `pip install "type_enforced<=1.10.2"`
172- **Python 3.9**: `pip install "type_enforced<=1.9.0"`
173- **Python 3.7 – 3.8**: `pip install "type_enforced==0.0.16"`
174</details>
175
176---
177
178## Usage Guide
179
180### 1. Functions and Methods
181
182Apply `@type_enforced.Enforcer` or `@type_enforced.FastEnforcer` to any callable. It validates positional arguments, keyword arguments, default parameters, and the return type.
183
184```python
185import type_enforced
186
187@type_enforced.Enforcer
188def process_user(user_id: int, tags: list[str], active: bool = True) -> dict[str, str | int]:
189    return {"user_id": user_id, "status": "active" if active else "inactive"}
190
191# Passing invalid types raises a descriptive TypeError:
192process_user("123", ["admin"])
193# TypeError: TypeEnforced Exception (process_user): Type mismatch for typed variable `user_id`.
194# Expected one of the following `[<class 'int'>]` but got `<class 'str'>` with value `123` instead.
195```
196
197### 2. Classes and Dataclasses
198
199Decorating a class with `@type_enforced.Enforcer` or `@type_enforced.FastEnforcer` automatically enforces types on all annotated methods (including `__init__`, `@classmethod`, and `@staticmethod`):
200
201```python
202import type_enforced
203from dataclasses import dataclass
204
205@type_enforced.Enforcer
206class Account:
207    def __init__(self, username: str, balance: float):
208        self.username = username
209        self.balance = balance
210
211    def deposit(self, amount: float) -> float:
212        self.balance += amount
213        return self.balance
214
215    @staticmethod
216    def validate_code(code: str) -> bool:
217        return len(code) == 6
218
219# Dataclasses work seamlessly:
220@type_enforced.Enforcer
221@dataclass
222class UserConfig:
223    retries: int
224    endpoint: str
225```
226
227To disable enforcement on a specific method within an enforced class:
228
229```python
230@type_enforced.Enforcer
231class Worker:
232    def standard_job(self, task: str) -> None:
233        pass
234
235    @type_enforced.Enforcer(enabled=False)
236    def high_throughput_job(self, data):
237        # Type enforcement skipped for maximum throughput
238        pass
239```
240
241### 3. Module-Level Enforcement (`ModuleEnforcer` or `FastModuleEnforcer`)
242
243Enforce typing across an entire module in a single line without decorating every function and class individually:
244
245```python
246# Place at the top of your module file (e.g., my_package/core.py)
247import type_enforced
248
249type_enforced.ModuleEnforcer()      # Complete validation across module
250# Or for fast O(1) sampled validation across the module:
251# type_enforced.FastModuleEnforcer()
252
253def add(a: int, b: int) -> int:
254    return a + b
255
256class Helper:
257    def run(self, flag: bool) -> str:
258        return "ok" if flag else "failed"
259```
260
261You can also enforce an imported module:
262
263```python
264import my_package
265import type_enforced
266
267type_enforced.ModuleEnforcer(my_package)
268# Or: type_enforced.FastModuleEnforcer(my_package)
269```
270
271
272> **Note:** By default, `submodules=True`, which recursively enforces all sub-packages/sub-modules in the same namespace (e.g. `mypkg.submodule`), while safely ignoring third-party and standard library imports.
273
274---
275
276## Supported Type Annotations
277
278`type_enforced` supports all standard Python 3.11+ typing constructs:
279
280### Standard Built-ins & Unions
281```python
282@type_enforced.Enforcer
283def fn(
284    a: int,
285    b: str | float,                    # Standard union syntax
286    c: int | None = None,              # Optional syntax
287) -> None:
288    pass
289```
290
291### Collections & Nested Generics
292```python
293@type_enforced.Enforcer
294def fn(
295    items: list[int | float],
296    mapping: dict[str, list[int]],      # Dicts require [KeyType, ValType]
297    unique_ids: set[str],
298    fixed_pair: tuple[str, int],        # Exact positional tuple: (str, int)
299    var_tuple: tuple[int, ...],         # Variable-length tuple
300) -> None:
301    pass
302```
303
304### Custom Classes & Subclass Inheritance
305By default, subclasses pass type validation (e.g. `Bar()` satisfies `Foo` if `class Bar(Foo)`):
306
307```python
308class Animal: pass
309class Dog(Animal): pass
310class Vehicle: pass
311
312@type_enforced.Enforcer
313def feed(animal: Animal) -> None:
314    pass
315
316feed(Animal())  # OK
317feed(Dog())     # OK (subclasses allowed)
318feed(Vehicle()) # Raises TypeError
319```
320
321To enforce uninitialized class objects (the class itself, rather than an instance), use `type[Animal]` (or `typing.Type[Animal]`):
322
323```python
324@type_enforced.Enforcer
325def make_instance(cls: type[Animal]) -> Animal:
326    return cls()
327```
328
329### Literals & Special Types
330```python
331from typing import Literal, Callable, Sized, Any
332
333@type_enforced.Enforcer
334def fn(
335    mode: Literal["read", "write"],        # Value check: must equal "read" or "write"
336    handler: Callable,                     # Functions, methods, generators
337    container: Sized,                      # list, dict, set, str, tuple, bytes, etc.
338    wildcard: Any,                         # Permissive bypass
339) -> None:
340    pass
341```
342
343- **Stacking Literals**: Literals combine with unions using OR logic (`int | Literal['auto']` allows any `int` or the literal string `'auto'`).
344
345### Modern Typing Constructs (PEP Standards)
346`type_enforced` comprehensively supports modern typing features from recent Python PEPs:
347
348```python
349from typing import (
350    Callable,
351    LiteralString,
352    Never,
353    NewType,
354    NoReturn,
355    Self,
356    TypeGuard,
357    TypeIs,
358    TypeVar,
359    TypedDict,
360)
361
362# 1. PEP 673: typing.Self
363class Builder:
364    @type_enforced.Enforcer
365    def set_name(self, name: str) -> Self:
366        self.name = name
367        return self
368
369# 2. PEP 589: typing.TypedDict (validates required keys & field types)
370class UserPayload(TypedDict):
371    id: int
372    name: str
373
374@type_enforced.Enforcer
375def create_user(payload: UserPayload) -> str:
376    return payload["name"]
377
378# 3. PEP 484: typing.NewType
379UserId = NewType("UserId", int)
380
381@type_enforced.Enforcer
382def get_user(user_id: UserId) -> None:
383    pass
384
385# 4. Subscripted Callables (PEP 484 & PEP 612)
386@type_enforced.Enforcer
387def apply_handler(callback: Callable[[int, str], bool]) -> None:
388    pass
389
390# 5. PEP 675: typing.LiteralString
391@type_enforced.Enforcer
392def run_query(sql: LiteralString) -> None:
393    pass
394
395# 6. PEP 484 / PEP 654: NoReturn and Never
396@type_enforced.Enforcer
397def terminate() -> NoReturn:
398    raise SystemExit(0)
399
400# 7. PEP 647 & PEP 742: TypeGuard and TypeIs
401@type_enforced.Enforcer
402def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
403    return all(isinstance(x, str) for x in val)
404
405# 8. TypeVar, ParamSpec, TypeVarTuple & PEP 695 (Python 3.12+)
406T = TypeVar("T", bound=int | float)
407
408@type_enforced.Enforcer
409def scale(val: T, factor: float) -> float:
410    return val * factor
411```
412
413### Collection & Nested Type Unions
414Unions of collection types are evaluated per-variant, enforcing that each container strictly satisfies one schema rather than allowing mixed elements:
415
416```python
417@type_enforced.Enforcer
418def process_data(
419    coords: tuple[int, str] | tuple[str, int],
420    lookup: dict[str, list[int]] | dict[str, int],
421    tags: list[int] | list[str],
422) -> None:
423    pass
424
425# Distinct collection schemas match:
426process_data((1, "north"), {"a": [1, 2]}, [1, 2, 3])  # OK
427process_data(("north", 1), {"a": 10}, ["a", "b"])  # OK
428
429# Mixed invalid structures fail:
430process_data((1, 1), {"a": 10}, [1, 2])  # Raises TypeError for coords
431process_data(
432    (1, "north"), {"a": 1, "b": [2]}, [1, 2]
433)  # Raises TypeError for lookup
434process_data((1, "north"), {"a": 10}, [1, "two"])  # Raises TypeError for tags
435```
436
437### Variadic Positional & Keyword Arguments
438`*args` and `**kwargs` are fully supported with clear, indexed error messages:
439
440```python
441@type_enforced.Enforcer
442def configure(*flags: str, **settings: int | bool) -> None:
443    pass
444
445configure("verbose", "debug", timeout=30, dry_run=True)  # OK
446configure("verbose", 123)  # Raises TypeError: Type mismatch for typed variable `flags[1]`
447configure(timeout="30s")   # Raises TypeError: Type mismatch for typed variable `settings['timeout']`
448```
449
450### Known Limitations / Currently Unsupported
451- Generic parameterization of `Sized` (e.g. `Sized[int]` — use `Sized` without inner type arguments)
452
453---
454
455## Value Validation with Constraints
456
457`type_enforced` allows post-type-check value constraints directly in type annotations.
458
459### Built-in `Constraint`
460Validate bounds, numeric comparisons, string patterns (regex), and inclusion/exclusion:
461
462```python
463import type_enforced
464from type_enforced.utils import Constraint
465
466@type_enforced.Enforcer
467def set_score(
468    score: int | Constraint(ge=0, le=100),
469    code: str | Constraint(pattern=r"^[A-Z]{3}[0-9]{4}$"),
470) -> bool:
471    return True
472
473set_score(85, "ABC1234")    # Passes
474set_score(105, "ABC1234")   # Raises TypeError (Constraint `Less Than Or Equal To (100)` not met)
475set_score(85, "invalid")    # Raises TypeError (Constraint `Regex Pattern Match` not met)
476```
477
478Available `Constraint` parameters:
479- `gt`, `lt`, `ge`, `le`, `eq`, `ne` (numeric / comparison bounds)
480- `pattern` (regular expression string match)
481- `includes`, `excludes` (membership checks)
482
483### Custom `GenericConstraint`
484Write arbitrary validation logic using custom predicates:
485
486```python
487import type_enforced
488from type_enforced.utils import GenericConstraint
489
490RGBColor = str | GenericConstraint({
491    "valid_hex_color": lambda c: c.startswith("#") and len(c) in (4, 7)
492})
493
494@type_enforced.Enforcer
495def render(color: RGBColor) -> None:
496    pass
497
498render("#ffffff")  # Passes
499render("red")      # Raises TypeError (Constraint `valid_hex_color` not met)
500```
501
502> **Note:** Constraints are evaluated *after* type checking. Constraints stack with unions: `int | Constraint(ge=0) | Constraint(le=10)`.
503
504---
505
506## Configuration Reference
507
508`@Enforcer`, `@FastEnforcer`, `ModuleEnforcer`, and `FastModuleEnforcer` accept the following configuration arguments:
509
510| Parameter | Type | Default | Description |
511|:---|:---:|:---:|:---|
512| `enabled` | `bool` | `True` | Toggle enforcement. Set `False` to bypass type checks (useful for production vs. debugging or per-method overrides). |
513| `strict` | `bool` | `True` | When `True`, raises `TypeError` on mismatch. When `False`, logs a warning to the console instead of raising. |
514| `clean_traceback` | `bool` | `True` | Filters internal `type_enforced` stack frames so unhandled tracebacks point directly to user code (see note below). |
515| `iterable_sample_pct` | `int, float, or str` | `100` (`'first'` for `Fast*`) | Sampling mode or percentage (0–100) of iterable items to validate. `'first'` checks the first item, `'last'` checks the last item (or first item for dicts/sets), `'bookend'` checks first and last items (first 2 items for dicts/sets), `'bookend_plus'` checks first, last, and a random middle item (first 2 items and 1 random item for dicts/sets), `'log'` checks a sample of ceil(log2(n)) items using a pseudo-random start offset and even steps across sequences (first ceil(log2(n)) items for dicts/sets), `0` checks 1 random item, and `1..100` checks the specified percentage (rounding up) starting at a pseudo-random offset within each step interval for sequences (first $N$ items for dicts/sets). `100` validates all elements. Note: `FastEnforcer` and `FastModuleEnforcer` strictly accept `'first'`, `'last'`, `'bookend'`, `'bookend_plus'`, `'log'`, or `0`. |
516| `only_typed` | `bool` | `False` | When `True`, raises an exception upon decoration if any parameter or return value lacks a type hint. |
517| `submodules` *(ModuleEnforcers only)* | `bool` | `True` | Recursively enforces all sub-packages/sub-modules in the same namespace. |
518
519### Configuration Options in Depth
520
521#### 1. Strict Typing Mode (`only_typed=True`)
522To catch unannotated parameters or missing return annotations across your codebase, enable `only_typed=True`. This raises a `TypeError` at definition time if any parameter (excluding `self`/`cls`) or the return type lacks an annotation:
523
524```python
525import type_enforced
526
527@type_enforced.Enforcer(only_typed=True)
528def calculate(a: int, b: int) -> int:
529    return a + b
530
531# Missing annotation on parameter `b` or missing return annotation raises immediately:
532@type_enforced.Enforcer(only_typed=True)
533def invalid_fn(a: int, b):
534    return a
535# TypeError: TypeEnforced Exception (invalid_fn): Untyped variable `b` found in function/method `invalid_fn`.
536```
537
538#### 2. Warning Mode (`strict=False`)
539Print warnings to the console instead of raising exceptions (useful for gradual adoption or debugging without breaking execution):
540
541```python
542@type_enforced.Enforcer(strict=False)
543def lenient_fn(x: int) -> int:
544    return x
545
546lenient_fn("not_an_int")
547# Logs: TypeEnforced Warning (lenient_fn): Type mismatch for typed variable `x`...
548# Returns "not_an_int" without raising an exception.
549```
550
551#### 3. Clean Tracebacks (`clean_traceback=True`)
552By default, `clean_traceback=True` temporarily hooks `sys.excepthook` when a type exception is raised, stripping internal `type_enforced` library frames so that unhandled script tracebacks point directly to the line of user code that caused the issue.
553
554> **Note on Interactive Terminals / REPLs:** In interactive environments (such as the Python REPL / PyREPL, IPython, or Jupyter notebooks), the shell wraps execution in an internal `try...except` loop and catches exceptions before they reach `sys.excepthook`. Consequently, interactive terminal sessions will still display the full traceback.
555
556#### 4. Sampled Validation (`FastEnforcer`, `FastModuleEnforcer`, `iterable_sample_pct`)
557For large or performance-critical collections, use `@type_enforced.FastEnforcer` or configure sampling instead of full iteration:
558- `'first'` (default for `FastEnforcer` / `FastModuleEnforcer`): Validates the first element in O(1) time (runs up to ~15x faster than Beartype).
559- `'last'`: Validates the last element in O(1) time for indexable sequences (`list`, `tuple`). For non-indexed collections like `dict` and `set`, `'last'` validates the first item to avoid reverse iteration and hash table lookup overhead.
560- `'bookend'`: Validates the first and last elements in O(1) time for sequences (the first 2 items for `dict` and `set`).
561- `'bookend_plus'`: Validates the first, last, and a random middle element in O(1) time for sequences (the first 2 items and 1 random item for `dict` and `set`).
562- `'log'`: For sequences (`list`, `tuple`), samples `ceil(log2(n))` items by picking a Weyl pseudo-random start offset and taking even step jumps across the collection. For `dict` and `set`, validates the first `ceil(log2(n))` items.
563- `0`: Validates one element chosen at random.
564- `1..99` (int, `Enforcer` / `ModuleEnforcer` only): Validates the specified percentage of items (rounding up). For sequences, selects a Weyl pseudo-random start offset in `[0, step - 1]` and takes even step jumps across the collection, giving every index an equal probability of being checked. For `dict` and `set`, validates the first `N` items.
565- `100`: Complete validation of all items across the collection.
566
567```python
568# Using FastEnforcer directly:
569@type_enforced.FastEnforcer
570def fast_check(items: list[int]) -> int:
571    return len(items)
572
573fast_check([1, 2, 3])           # OK
574fast_check(["bad_first", 2, 3])  # Raises TypeError
575
576# Or configure Enforcer with a specific sample mode:
577@type_enforced.Enforcer(iterable_sample_pct="last")
578def check_last(items: list[int]) -> int:
579    return len(items)
580```
581
582
583
584---
585
586## Production Best Practices
587
588### Multi-Threaded Services & Web Frameworks (`clean_traceback=False`)
589By default, `clean_traceback=True` temporarily hooks `sys.excepthook` to filter internal library frames for standalone scripts. In concurrent multi-threaded environments and applications using centralized error handlers, consider setting `clean_traceback=False`:
590
591```python
592import type_enforced
593
594@type_enforced.Enforcer(clean_traceback=False)
595def process_request(user_id: int, tags: list[str]) -> dict:
596    return {"user_id": user_id, "tags": tags}
597```
598
599---
600
601## Contributing
602
603Contributions are welcome!
604
605### Development Setup
606
607We use [uv](https://docs.astral.sh/uv/) for dependency management and testing in a Unix-based environment (Linux, macOS, or WSL2 on Windows).
608
609```bash
610# Clone the repository
611git clone https://github.com/connor-makowski/type_enforced.git
612cd type_enforced
613
614# Install dev dependencies
615uv sync --extra dev
616```
617
618### Development Commands
619
620| Command | Description |
621|:---|:---|
622| `uv run pytest` | Run tests in local environment |
623| `uv run pytest -v` | Run tests with verbose output |
624| `uv run nox` | Run test suite across Python 3.11–3.14 (C++ and pure-Python fallback) |
625| `uv run nox -s tests-3.14` | Run test suite on a specific Python version |
626| `uv run python utils/minibench.py` | Run quick performance at a glance benchmark |
627| `uv run python utils/cpp_vs_python_bench.py` | Run C++ accelerated vs pure Python benchmark |
628| `uv run python utils/prettify.py` | Auto-format with `autoflake` and `black` (80 col) |
629
630### Guidelines
6311. Fork the repo and create your branch from `main`.
6322. Ensure all tests pass across versions (`uv run nox`).
6333. Format code before committing (`uv run python utils/prettify.py`).
6344. Keep commits atomic and clearly described.
6355. Submit a pull request.
636
637---
638
639## Academic Citation
640
641If you use `type_enforced` in academic research, please cite our [JOSS paper](https://doi.org/10.21105/joss.08832):
642
643```bibtex
644@article{Makowski2026,
645  doi = {10.21105/joss.08832},
646  url = {https://doi.org/10.21105/joss.08832},
647  year = {2026},
648  publisher = {The Open Journal},
649  volume = {11},
650  number = {118},
651  pages = {8832},
652  author = {Connor Makowski},
653  title = {type_enforced: A pure Python runtime type enforcer},
654  journal = {Journal of Open Source Software}
655}
656```
657
658---
659
660## License
661
662Distributed under the [MIT License](https://opensource.org/licenses/MIT). See `LICENSE` for details.
663"""
664
665from .enforcer import Enforcer, FastEnforcer, FunctionMethodEnforcer
666from .module import ModuleEnforcer, FastModuleEnforcer
667from .utils import has_cpp