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"
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-monkfocuses 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 integer123. - ⏳ Deferred Validation: Other frameworks force crashes on bad data.
iron-monkcaptures 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(f"'{field}' must be an even number.")
except TypeError:
raise TypeError(f"'{field}' 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"'{field}' must be divisible by {self.divisor}.")
except TypeError:
raise TypeError(f"'{field}' 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.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| iron_monk-0.1.1.tar.gz | 16.0 kB | With provenance | Details for iron_monk-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| iron_monk-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for iron_monk-0.1.1-py3-none-any.whl |
Total release size: 28.3 kB
Release files / iron_monk-0.1.1.tar.gz
| Download URL | iron_monk-0.1.1.tar.gz |
|---|---|
| Size | 16.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f27567d657771ec721d0e9e11e8c102492369d3a1b337b0b6c37900fe8819657
|
|
BLAKE2b-256 checksum How to use checksums |
81b23d6a3254e21256e6bc01cde8110bb1c21310e0a01cb29554bc18d4fb5a76
|
| 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 logRelease files / iron_monk-0.1.1-py3-none-any.whl
| Download URL | iron_monk-0.1.1-py3-none-any.whl |
|---|---|
| Size | 12.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
dc419a98a162759431391335858aae78df870e51dadbfa20216b63bcb8fb8ed4
|
|
BLAKE2b-256 checksum How to use checksums |
4720e57bb9e7ac719245b25fc0fd3e1dfbbf8bed371370c0136f21066fce21d6
|
| 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 logSecurity for iron-monk 0.1.1
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.
Attestation for iron_monk-0.1.1.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 logA 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.