Skip to main content
iron-monk logo

iron-monk

A minimalist, strict validation library for Python dataclasses.

CI/CD PyPI version Python Versions License Coverage: 100% Zero Dependencies

Installation

pip install iron-monk
# Or with modern package managers:
uv add iron-monk
poetry add iron-monk

Quickstart

Define your models using the @monk decorator and wrap your types in Annotated constraints.

from typing import Annotated
from monk import monk, validate
from monk.constraints import Email, Interval
from monk.exceptions import ValidationError

@monk
class User:
    email: Annotated[str, Email]
    age: Annotated[int, Interval(ge=18)]

# 1. Instantiate
user = User(email="bad-email", age=12)

# 2. Validate
try:
    validate(user)
except ValidationError as e:
    print(e.errors)
    # [{'field': 'email', 'message': "..."}, {'field': 'age', 'message': "..."}]

# 3. Use it safely
valid_user = validate(User(email="test@domain.com", age=25))
print(valid_user.email) # "test@domain.com"

💡 Looking for real-world usage? Check out the examples directory to see how iron-monk integrates flawlessly with Strawberry GraphQL, Application Configuration, and more!

Why iron-monk?

The Python ecosystem is dominated by heavy validation frameworks. iron-monk is built for a completely different philosophy:

  • 🎯 Scope: Do one thing well. Unlike libraries that parse, coerce, and serialize, iron-monk focuses strictly on validation.
  • 🪶 Zero Dependencies: Pure Python. No compiled Rust binaries or bloated environments.
  • 🧬 Zero Inheritance: Just decorate a standard class with @monk. No massive base classes polluting your namespace.
  • 🛡️ Strict (No Magic): We don't secretly coerce the string "123" into the integer 123.
  • ⏳ Deferred Validation: Other frameworks force crashes on bad data. iron-monk captures it in a guarded state, giving you control over when validation occurs.

The Constraint Toolkit

iron-monk comes fully equipped. All constraints elegantly handle None (nullability is left to the type checker) and throw native TypeErrors if applied to incompatible data structures.

Strings

from typing import Annotated
from monk import monk
from monk.constraints import Match, StartsWith, EndsWith, LowerCase, UpperCase, IsDigit, IsAscii

@monk
class TextData:
    sku: Annotated[str, Match(r"^PROD-\d+$")]
    role: Annotated[str, StartsWith("admin_")]
    file_name: Annotated[str, EndsWith(".csv")]
    username: Annotated[str, LowerCase]
    department_code: Annotated[str, UpperCase]
    pin_code: Annotated[str, IsDigit]
    bio: Annotated[str, IsAscii]

Numeric

from typing import Annotated
from monk import monk
from monk.constraints import Interval, MultipleOf, NonNegative, IsFinite, IsNan, IsInfinite

@monk
class Metrics:
    percentage: Annotated[float, Interval(ge=0, le=100)] # 0 <= x <= 100
    batch_size: Annotated[int, MultipleOf(5)]
    count: Annotated[int, NonNegative]
    temperature: Annotated[float, IsFinite]
    missing_value: Annotated[float, IsNan]
    limit: Annotated[float, IsInfinite]

Collections & Iterables

from typing import Annotated
from monk import monk
from monk.constraints import Len, Contains, OneOf, Unique, Each, LowerCase

@monk
class Group:
    password: Annotated[str, Len(min_len=8, max_len=64)]
    tags: Annotated[list[str], Contains("admin")]
    status: Annotated[str, OneOf(["active", "pending", "closed"])]
    emails: Annotated[list[str], Unique]
    matrices: Annotated[list[list[int]], Unique] # Safely handles unhashable inner items!
    
    # Apply constraints to every element in a collection:
    usernames: Annotated[list[str], Each(LowerCase, Len(min_len=3))]

Formats & Networking

import uuid
from typing import Annotated
from monk import monk
from monk.constraints import Email, URL, IPAddress, UUID

@monk
class ServerNode:
    contact: Annotated[str, Email]
    webhook: Annotated[str, URL]
    public_ip: Annotated[str, IPAddress]
    session_id: Annotated[str | uuid.UUID, UUID]

Logical & Time

import datetime
from typing import Annotated
from monk import monk
from monk.constraints import Predicate, Not, Email, IsUTC

@monk
class Event:
    # Turn any boolean function into a constraint
    even_number: Annotated[int, Predicate(lambda x: x % 2 == 0)]
    # Invert any other constraint
    not_an_email: Annotated[str, Not(Email)]
    # Built-in timezone strictness
    created_at: Annotated[datetime.datetime, IsUTC]

Advanced Features

Deferred vs. Instant Validation (Fail-Fast)

By default, iron-monk defers validation, placing objects into a guarded state until validate() is explicitly called.

If you prefer the traditional "fail-fast" behavior (where objects validate and crash instantly upon instantiation with a ValidationError), you have three ways to enable it:

1. Per-Class

from typing import Annotated
from monk import monk
from monk.constraints import Email

@monk(deferred_validation=False)
class User:
    email: Annotated[str, Email]
    
user = User(email="bad") # Raises ValidationError instantly

2. Global Configuration

from monk import settings

settings.deferred_validation = False # Applies to all @monk classes

3. Environment Variable (Production Friendly)

export MONK_DEFERRED_VALIDATION=false

Deep Recursion

Nested models are natively supported and fully recursive. If validation fails deep within a tree of lists and dictionaries, the error payload dynamically builds the exact dot-notation path.

from typing import Annotated
from monk import monk, validate
from monk.exceptions import ValidationError
from monk.constraints import OneOf

@monk
class Config:
    env: Annotated[str, OneOf(["dev", "prod"])]

@monk
class Server:
    configs: list[Config]

server = Server(configs=[Config(env="dev"), Config(env="TEST")])

try:
    validate(server)
except ValidationError as e:
    print(e.errors[0]["field"]) 
    # Output: "configs[1].env"

Custom Constraints

Building your own constraints is stupidly simple thanks to pure duck-typing. You don't even need to inherit from a base class. Just write a validate() method and raise a standard ValueError or TypeError.

from typing import Any, Annotated
from monk import monk

class IsEven:
    def validate(self, field: str, value: Any) -> None:
        if value is None:
            return
            
        try:
            if value % 2 != 0:
                raise ValueError("Must be an even number.")
        except TypeError:
            raise TypeError("Must be a number.")

# Use it!
@monk
class User:
    user_id: Annotated[int, IsEven]

If your constraint needs parameters, use our @constraint wrapper to instantly turn it into a high-performance dataclass!

from typing import Any, Annotated
from monk import constraint, monk

@constraint # This is just a convenience decorator. This equates to `@dataclass(frozen=True, slots=True)`
class DivisibleBy:
    divisor: int

    def validate(self, field: str, value: Any) -> None:
        if value is None:
            return
            
        try:
            if value % self.divisor != 0:
                raise ValueError(f"Must be divisible by {self.divisor}.")
        except TypeError:
            raise TypeError("Must be a number.")

# Use it!
@monk
class User:
    user_id: Annotated[int, DivisibleBy(5)]

License

MIT

Metadata

Release files for iron-monk 0.1.2

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

Source distribution (sdist)

Source distribution for iron-monk 0.1.2
File Size Uploaded Provenance Actions
iron_monk-0.1.2.tar.gz 16.2 kB With provenance Details for iron_monk-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for iron-monk 0.1.2
File Interpreter ABI Platform Actions
iron_monk-0.1.2-py3-none-any.whl Python 3 none any Details for iron_monk-0.1.2-py3-none-any.whl

Total release size: 28.8 kB

Release files / iron_monk-0.1.2.tar.gz

Download URL iron_monk-0.1.2.tar.gz
Size 16.2 kB
Tags Source
SHA-256 checksum
How to use checksums
3fea304260059c02b3e9a9839557d3413b5c36c694e320613a103e5235f1470f
BLAKE2b-256 checksum
How to use checksums
d4b5e29f907733a5fdae7b1a89069c9cc6f4dbc89b1458482ec3fd5544c28538
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 17, 2026.

Transparency log

Release files / iron_monk-0.1.2-py3-none-any.whl

Download URL iron_monk-0.1.2-py3-none-any.whl
Size 12.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f8925979920d3e3fe4cb71b4619dccb341b7c2d99f66434ed13b13eff1bc54d2
BLAKE2b-256 checksum
How to use checksums
a0dd511f978f31c08e87590c4374c04a23aa6fce8bc4075f46dd4bf95980ba22
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 17, 2026.

Transparency log

Security for iron-monk 0.1.2

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for iron_monk-0.1.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 17, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files Full provenance

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