Runtype: Runtime Type Validation and Multiple Dispatch

0.5.3 · active · verified Thu Apr 16

Runtype is a Python library providing utilities for fast run-time type validation and multiple dispatch. It enhances Python's built-in `dataclasses` with runtime type validation and automatic casting, offers smart alternatives to `isinstance` and `issubclass` for complex types, and implements a performant multiple-dispatch decorator. The library is currently at version 0.5.3, with a regular release cadence addressing bug fixes and performance improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic runtime type validation using `isa` and shows how to define a type-safe dataclass using `runtype.dataclass`. It includes examples of both successful validation and instances where validation fails, raising a TypeError.

from runtype import isa
from runtype.dataclass import dataclass

# Example 1: Runtime type validation
assert isa({'a': 1, 'b': 2}, dict[str, int]) == True
assert isa([1, 'a', 3], list[int | str]) == True
assert not isa({'a': 'b'}, dict[str, int]) == True

# Example 2: Type-safe dataclass
@dataclass
class User:
    name: str
    age: int
    email: str

try:
    user = User(name='Alice', age=30, email='alice@example.com')
    print(f"Valid user: {user.name}")
except TypeError as e:
    print(f"Validation error: {e}")

try:
    # This will raise a TypeError due to 'age' being a string
    invalid_user = User(name='Bob', age='twenty', email='bob@example.com')
    print(f"Invalid user: {invalid_user.name}")
except TypeError as e:
    print(f"Validation error for invalid user: {e}")

view raw JSON →