Typeguard

raw JSON →
4.5.1 verified Tue May 12 auth: no python install: verified quickstart: verified

Typeguard is a Python library that provides run-time type checking for functions and methods defined with PEP 484 type annotations, as well as for arbitrary objects. It acts as an additional layer of type safety alongside static type checkers like MyPy, catching type violations that can only be detected at run time. Currently at version 4.5.1, the library is actively maintained with regular updates.

pip install typeguard
breaking Version 4.5.0 introduced a breaking change where `check_argument_types()` started receiving an unexpected keyword argument 'memo', causing issues in downstream libraries.
fix If encountering `TypeError: check_argument_types() got an unexpected keyword argument 'memo'`, consider downgrading to `typeguard==4.4.1` or refactoring code to use `@typechecked` or `check_type` which are less susceptible to this specific issue.
gotcha The `@typechecked` decorator becomes a no-op when Python is run in optimized mode (`python -O` or by setting the `PYTHONOPTIMIZE` environment variable). This can lead to silent disabling of runtime type checks in production environments.
fix Be aware of this behavior and explicitly configure type checking for production if it's critical. If you need runtime checks in optimized mode, you would need to use `check_type()` explicitly or ensure the import hook is installed in a way that bypasses this optimization behavior (which is not the default for `@typechecked`).
deprecated Direct use of `check_argument_types()` and `check_return_type()` has limitations, such as not working reliably with dynamically defined type hints (e.g., in nested functions) and being less comprehensive than the `@typechecked` decorator.
fix Prefer using the `@typechecked` decorator for functions and methods, or the `check_type()` function for individual value checks, as these provide more robust and reliable runtime type enforcement.
breaking Typeguard has dropped support for Python 3.8 in recent major versions (e.g., in the 4.x series).
fix Ensure your project runs on Python 3.9 or newer to use the latest versions of Typeguard. The `requires_python` metadata on PyPI reflects this, currently `>=3.9`.
gotcha Typeguard enforces runtime type checks and will raise a `typeguard.TypeCheckError` when an argument or return value does not match its annotated type at runtime. This is Typeguard's core functionality.
fix Ensure that all values passed to functions or returned from them strictly adhere to their type annotations to avoid `TypeCheckError`. Use static type checkers (e.g., MyPy) during development to catch such issues preemptively, and implement careful input validation if external data is involved.
gotcha Typeguard raises `typeguard.TypeCheckError` when a function argument or return value does not match its annotated type. This is its core functionality and will prevent execution with incorrect types.
fix Ensure that arguments passed to type-checked functions and their return values strictly conform to their specified type hints to avoid `TypeCheckError`.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.32s 18.4M
3.10 alpine (musl) - - 0.33s 18.4M
3.10 slim (glibc) wheel 1.6s 0.21s 19M
3.10 slim (glibc) - - 0.20s 19M
3.11 alpine (musl) wheel - 0.42s 20.3M
3.11 alpine (musl) - - 0.47s 20.3M
3.11 slim (glibc) wheel 1.6s 0.36s 21M
3.11 slim (glibc) - - 0.34s 21M
3.12 alpine (musl) wheel - 0.63s 12.2M
3.12 alpine (musl) - - 0.67s 12.2M
3.12 slim (glibc) wheel 1.5s 0.64s 13M
3.12 slim (glibc) - - 0.62s 13M
3.13 alpine (musl) wheel - 0.64s 11.9M
3.13 alpine (musl) - - 0.69s 11.8M
3.13 slim (glibc) wheel 1.6s 0.58s 12M
3.13 slim (glibc) - - 0.60s 12M
3.9 alpine (musl) wheel - 0.37s 18.2M
3.9 alpine (musl) - - 0.42s 18.2M
3.9 slim (glibc) wheel 2.0s 0.34s 19M
3.9 slim (glibc) - - 0.31s 19M

This quickstart demonstrates using the `@typechecked` decorator on both functions and methods. It shows successful type checking and how `typeguard` raises a `TypeError` when type annotations are violated at runtime.

from typeguard import typechecked
from typing import List

@typechecked
def process_data(data: List[int], multiplier: float) -> List[float]:
    """Processes a list of integers, multiplies each by a float, and returns a list of floats."""
    return [item * multiplier for item in data]

@typechecked
class MyCalculator:
    def __init__(self, offset: int):
        self.offset = offset

    def add(self, a: int, b: int) -> int:
        return a + b + self.offset


# --- Successful usage ---
print(f"Processed data: {process_data([1, 2, 3], 2.5)}") # Expected: [2.5, 5.0, 7.5]
calculator = MyCalculator(offset=10)
print(f"Calculator sum: {calculator.add(5, 7)}") # Expected: 22

# --- Intentional type errors (will raise TypeError) ---
try:
    process_data([1, '2', 3], 2.5) # data contains a string instead of int
except TypeError as e:
    print(f"Caught expected error (list item type): {e}")

try:
    process_data([1, 2, 3], '2.5') # multiplier is a string instead of float
except TypeError as e:
    print(f"Caught expected error (argument type): {e}")

try:
    calculator.add(5, 'seven') # b is a string instead of int
except TypeError as e:
    print(f"Caught expected error (method argument type): {e}")