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"

Real-world examples

iron-monk is designed to drop seamlessly into any modern Python ecosystem. Check out the examples directory for production-ready scripts:

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
import pathlib

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

@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]
    # For file paths, you can use Path OR str
    config_file: Annotated[pathlib.Path, IsFile]
    output_dir: Annotated[str, IsDir]

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.3

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.3
File Size Uploaded Provenance Actions
iron_monk-0.1.3.tar.gz 16.8 kB With provenance Details for iron_monk-0.1.3.tar.gz

Built distribution (wheel)

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

Total release size: 29.8 kB

Release files / iron_monk-0.1.3.tar.gz

Download URL iron_monk-0.1.3.tar.gz
Size 16.8 kB
Tags Source
SHA-256 checksum
How to use checksums
52374e61234290f543e4fa7accfe96428b4d2ce5342b8a27e169b9c488ff9c09
BLAKE2b-256 checksum
How to use checksums
9c9ef6fafdc2f7e5aab66e82e9ba69bb10a88f2c3480f6af3b75b2c1ff7a5fc7
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 18, 2026.

Transparency log

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

Download URL iron_monk-0.1.3-py3-none-any.whl
Size 13.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
59571e1a0f09904b5bfe67d2a292f17819ef8f5ad9872e170a0bf84979b8d31c
BLAKE2b-256 checksum
How to use checksums
9213b764a51b18e33933d9c520541555a86df1dada70802a2dc4653af27bdb07
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 18, 2026.

Transparency log

Security for iron-monk 0.1.3

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.3.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 18, 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.3 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