Skip to content

API Reference

Auto-generated from the source. For prose with examples, see Core Concepts and the Constraints catalog.

Decorators

monk.decorators.monk(obj=None, *, defer=None, **dataclass_kwargs)

monk(obj: type[T]) -> type[T]
monk(
    *, defer: bool | None = None, **dataclass_kwargs: Any
) -> Callable[[type[T]], type[T]]
monk(obj: Callable[P, R]) -> Callable[P, R]

The primary decorator for iron-monk.

Transforms a class into a validated, guarded dataclass, OR validates function arguments and return values.

Parameters:

Name Type Description Default
obj Any

The class or function to decorate.

None
defer bool | None

Whether to defer validation until validate() is called. Defaults to the global setting.

None
**dataclass_kwargs Any

Additional keyword arguments passed to dataclasses.dataclass when decorating a class.

{}

Returns:

Type Description
Any

The wrapped class or function.

Raises:

Type Description
TypeError

If the decorated object is neither a class nor a function.

monk.decorators.constraint(cls=None, *, frozen=True, slots=True, **kwargs)

constraint(cls: type[T]) -> type[T]
constraint(
    *,
    frozen: bool = True,
    slots: bool = True,
    **kwargs: Any,
) -> Callable[[type[T]], type[T]]

Convenience decorator for custom constraints.

Creates a high-performance dataclass (frozen and slotted by default). Intercepts the validation method to safely inject and format custom error messages.

Parameters:

Name Type Description Default
cls type[T] | None

The class to decorate.

None
frozen bool

Whether the resulting dataclass should be frozen. Defaults to True.

True
slots bool

Whether the resulting dataclass should use slots. Defaults to True.

True
**kwargs Any

Additional keyword arguments passed to dataclasses.dataclass.

{}

Returns:

Type Description
type[T] | Callable[[type[T]], type[T]]

The transformed constraint class.

Validation Entry Points

monk.operations.validate(instance, *, context=None)

Validates a Monk dataclass instance.

Executes all field-level constraints. If all field-level constraints pass, it then executes the model-level __monk_validate__ hook if present. Returns the instance so it can be used inline or reassigned.

Parameters:

Name Type Description Default
instance T

The instantiated Monk dataclass to validate.

required
context Mapping[str, Any] | None

Read-only mapping used to resolve Ctx(key) markers inside constraints. Also forwarded to __monk_validate__ when its signature accepts a second positional argument. Defaults to None.

None

Returns:

Name Type Description
T T

The validated dataclass instance, which is now fully unlocked for attribute access.

Raises:

Type Description
TypeError

If the provided instance is not a valid Monk dataclass, or if an async cross-field hook is used.

ValidationError

If the instance fails validation.

MissingContextError

If a constraint references Ctx(...) but no context was provided.

monk.operations.validate_value(value, constraint, *constraints, field_name='value')

Validates a single value against one or more constraints, inline.

Convenience helper for ad-hoc validation outside a @monk dataclass — useful inside controllers, scripts, or one-shot checks. Aggregates every constraint failure into a single ValidationError (same semantics as validate()), not fail-fast.

Parameters:

Name Type Description Default
value Any

The value to validate.

required
constraint MonkConstraint | type[MonkConstraint]

First constraint (required). Instance or bare class.

required
*constraints MonkConstraint | type[MonkConstraint]

Additional constraints (instances or bare classes).

()
field_name str

Field name used in produced ErrorDict entries. Defaults to "value".

'value'

Raises:

Type Description
ValidationError

If any constraint fails. error.errors contains one ErrorDict per failing constraint.

TypeError

If called with no constraints (caught at the Python call site by the required constraint parameter).

monk.operations.validate_dict(data, schema, *, partial=False, drop_extra_keys=False, context=None)

Validates a raw dictionary against a TypedDict or Dataclass schema without instantiating an object.

Parameters:

Name Type Description Default
data dict[str, Any]

The raw dictionary payload to validate.

required
schema type

The TypedDict or Dataclass schema containing the validation rules.

required
partial bool

If True, ignores keys that are missing from the payload (useful for PATCH requests). Defaults to False.

False
drop_extra_keys bool

If True, strips any keys not explicitly defined in the schema. Defaults to False.

False
context Mapping[str, Any] | None

Read-only mapping used to resolve Ctx(key) markers inside constraints. Defaults to None.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The validated (and optionally sanitized) dictionary.

Raises:

Type Description
ValidationError

If the dictionary fails any validation constraints or contains unrecognized keys (when drop_extra_keys is False).

MissingContextError

If a constraint references Ctx(...) but no context was provided.

monk.operations.validate_stream(stream, *constraints)

Lazily validates an iterable/generator on the fly without consuming it entirely.

Yields items one by one, raising a ValidationError instantly if an item fails.

Parameters:

Name Type Description Default
stream Iterable[Any]

The iterable or generator to validate.

required
*constraints Any

A variable number of constraint instances or classes to apply to each item.

()

Yields:

Name Type Description
Any Any

The original item from the stream, assuming it passed validation.

Raises:

Type Description
ValidationError

If any individual item fails validation.

monk.operations.validate_async_stream(stream, *constraints) async

Lazily validates an async iterable/generator on the fly without consuming it entirely.

Yields items one by one, raising a ValidationError instantly if an item fails.

Parameters:

Name Type Description Default
stream AsyncIterable[Any]

The asynchronous iterable or generator to validate.

required
*constraints Any

A variable number of constraint instances or classes to apply to each item.

()

Yields:

Name Type Description
Any AsyncIterator[Any]

The original item from the async stream, assuming it passed validation.

Raises:

Type Description
ValidationError

If any individual item fails validation.

Built-in Constraints

monk.constraints

AllEqual

Validates that every element in an iterable is equal to the others. Empty iterables pass.

AllOf

Validates that a value satisfies all of the given constraints.

AnyOf

Validates that a value satisfies at least one of the given constraints.

Base64

Validates a Base64 encoded string structurally.

Blank

Validates that a string is empty or contains only whitespace.

CSV

Validates a delimited string and applies constraints to each extracted element.

Contains

Validates that a collection or string contains a specific item/substring.

ContainsKeys

Validates that a dictionary contains all the specified keys.

CreditCard

Validates a credit card number using Luhn checksum and length 13-19.

Cron

Validates a cron expression structurally (supports standard 5-field and AWS 6-field formats).

Ctx

A marker used to reference a value from the validation context.

Resolved at validation time from the context mapping passed to validate(), validate_dict(), or instance.validate(). If the mapping is missing the key, a ValidationError is raised on the enclosing field. If no context was provided at all, a MissingContextError is raised (programmer error).

Example

from typing import Annotated from monk import monk, validate from monk.constraints import Interval, Ctx

@monk class AgeGate: age: Annotated[int, Interval(gte=Ctx("min_age"))]

validate(AgeGate(age=15), context={"min_age": 18}) # raises

DataURI

Validates a data URI per RFC 2397 (e.g., data:image/png;base64,iVBORw0...).

DecimalPlaces

Validates that a numeric or numeric-string has at most max_places digits after the decimal point.

Accepts int, float, decimal.Decimal, or a numeric string. Trailing zeros count as places (so Decimal("1.50") has 2 places).

DictOf

Validates arbitrary dictionaries by applying constraints to their keys and/or values.

Each

Validates that every element in an iterable satisfies all the given constraints.

Email

Validates an email address using the HTML5 living-standard atom regex.

Local-part accepts the full set of unquoted characters permitted by RFC 5322 atoms (a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-), the same set used by the WHATWG HTML <input type="email"> validator and most modern web forms. The domain must still be a dotted hostname (at least one .) so single-label hosts like user@localhost are rejected — match what real mail servers accept. Quoted local parts and IP-literal domains (RFC 5321 §4.1.3) are intentionally out of scope; if you need them, compose AnyOf with a custom Match constraint.

Eq

Validates that a value is strictly equal to another value or Ref.

Even

Validates that an integer is even.

ExactLen

Validates that a sized collection or string is exactly a specific length.

FileSize

Validates that a bytes / bytearray value's length falls within [min_size, max_size].

Intended for file-upload bodies. Both bounds are inclusive; either may be None to skip that side of the check. Unlike :class:MaxBytes, this does not accept str — mixing string byte-length and file-body length would hide bugs.

Future

Validates that a datetime or date is in the future.

Hash

Validates a hex-encoded hash digest of fixed length per algorithm.

Supported algorithms: md5, sha1, sha224, sha256, sha384, sha512, blake2s, blake2b.

HexColor

Validates a hexadecimal color string (e.g., #FFF, #123456).

HexString

Validates that a string contains only hex characters (optionally of a fixed length).

Hostname

Validates an RFC 1123 hostname (labels 1-63 chars, alphanum + hyphen, total ≤253).

HttpURL

Validates a URL restricted to the http or https scheme.

IPAddress

Validates that a value is a valid IPv4 or IPv6 address

ISBN

Validates ISBN-10 or ISBN-13 with checksum verification.

Interval

Numeric or Comparable Interval bounds

IsDir

Validates that a string or Path object points to an existing directory.

IsFile

Validates that a string or Path object points to an existing file.

IsISO8601

Validates that a string is a valid ISO 8601 date or datetime.

JSON

Validates that a string can be safely parsed as JSON.

JWT

Validates a JSON Web Token (JWT) structurally (Header.Payload.Signature).

LatLong

Validates a tuple or list of exactly two floats: (latitude, longitude).

MacAddress

Validates a standard MAC address (e.g., 00:1A:2B:3C:4D:5E).

MagicBytes

Validates that a bytes value's content matches a known file-format signature.

Sniffs the leading bytes of value against an internal registry of magic signatures and asserts the detected mime is in allowed (if provided). Defends against extension- and header-based mime spoofing.

Supply extra_signatures to register custom formats. Each entry maps a mime string to a single AND-pattern (tuple of (bytes, offset) pairs that must all match).

Allowed list uses mime strings, e.g. ("image/png", "image/jpeg"). A single mime string is also accepted as shorthand (e.g. allowed="image/png"). When allowed=None, any recognized format passes.

allowed also accepts Ref("other_field") / Ctx("key") markers so the whitelist can be sourced from a sibling field or validation context. The resolved value may be either a single mime string or an iterable of strings.

Match

Validates that a string matches a specific Regular Expression.

MaxBytes

Validates that a string's UTF-8 encoded length is at most max_bytes.

Accepts str (encoded as UTF-8 to count) or raw bytes / bytearray (counted directly). Useful for database column limits and API payload guards where char count diverges from byte count for multibyte characters (CJK, emoji, accented Latin).

MimeType

Validates a MIME type per RFC 6838 (e.g., application/json, text/html; charset=utf-8).

Nested

Validates a nested dictionary against a TypedDict or Dataclass schema.

NoWhitespace

Validates that a string contains no whitespace characters.

NonZero

Validates that a numeric value is not zero.

Not

Inverts the logic of another constraint.

NotNull

A marker constraint to explicitly forbid None values.

Nullable

A marker constraint to explicitly allow None values.

Odd

Validates that an integer is odd.

OneOf

Validates that a value is an exact member of a predefined set of choices.

PEMBlock

Structurally validates a PEM-encoded block (e.g., X.509 certificate, RSA key, SSH public key).

Checks the -----BEGIN <LABEL>----- / -----END <LABEL>----- envelope and Base64 body. Performs no cryptographic verification — use a crypto library for that.

Past

Validates that a datetime or date is in the past.

PathSafe

Validates a filename: no path separators, no .. segments, no null bytes, not empty, not ./...

PhoneE164

Validates a phone number in E.164 structural format (e.g., +14155552671).

Port

Validates a standard network port number (1-65535).

PowerOfTwo

Validates that a positive integer is a power of two (1, 2, 4, 8, ...).

Predicate

Validates that a value satisfies a given boolean-returning function.

Ref

A marker used to reference another field dynamically.

SemVer

Validates standard Semantic Versioning.

SingleLine

Validates that a string contains no newline or carriage-return characters.

Slug

Validates a URL-safe slug (lowercase alphanumeric and hyphens).

Sorted

Validates that an iterable is sorted (ascending by default, descending if reverse=True).

Subset

Validates that all elements in a collection are within a predefined set of choices.

Switch

Branches validation by the value of a Ref-resolved sibling field.

cases maps discriminator values to constraints. If the resolved value of field is a key in cases, that constraint is applied to the current field's value. Otherwise default is applied if provided; if no default is set, an unknown discriminator raises a ValueError.

Example

@monk class Notification: channel: str target: Annotated[ str, Switch( field=Ref("channel"), cases={"email": Email, "sms": Match(r"^+\d+")}, default=Len(min_len=1), ), ]

TimeOfDay

Validates a 24-hour time-of-day string in HH:MM or HH:MM:SS format.

TimezoneName

Validates that a string is a valid IANA timezone name (e.g., 'America/New_York').

Trimmed

Validates that a string has no leading or trailing whitespace.

URL

Validates that a string is a properly formatted URL

UUID

Validates that a value is a valid UUID string or object

Unique

Validates that all elements in a collection are unique.

When

Conditional validation: applies then (or else_) based on a test against a Ref-resolved sibling field.

field is typically a Ref to another field on the same model. At validation time, the blueprint compiler resolves the Ref and runs test against the resolved value. If test passes, then is applied to the current field's value; if test raises, else_ (when provided) is applied instead.

Example

@monk class Order: payment_method: str cc_number: Annotated[ str | None, When(field=Ref("payment_method"), test=Eq("credit"), then=Len(min_len=16, max_len=16)), ]

Exceptions

monk.exceptions

MissingContextError

Bases: Exception

Raised when a constraint references Ctx(...) but validate() / validate_dict() was called without a context= argument.

Note: a missing key inside a provided context is reported through the normal ValidationError aggregation, not this exception. This is reserved for the programmer error of forgetting to pass context entirely.

UnvalidatedAccessError

Bases: Exception

Raised when attempting to access an attribute on a Monk object before validate() has been successfully called.

ValidationError

Bases: Exception

flatten()

Returns a flat list of formatted error strings.

to_rfc7807(status=400, title='Validation Error', type_uri='about:blank', detail="The provided data is invalid. See 'errors' for specific details.", instance=None)

Formats the errors into an RFC 7807 compliant dictionary for HTTP APIs.

Settings

monk.config

MonkSettings

Global configuration settings for iron-monk.