Beartype is an open-source, pure-Python, PEP-compliant, near-real-time runtime-static type-checker. It emphasizes efficiency, portability, and readability, ensuring O(1) non-amortized worst-case runtime complexity with negligible constant factors. The library has no runtime dependencies and is actively maintained with frequent patch releases addressing compatibility and bug fixes, as evidenced by its rapid `0.22.x` release cycle.
Install & Compatibility
Where this runs
tested against v0.22.9 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.925 runs
installs and imports cleanly · install 0.0s · import 0.304s · 26.8MB
glibcpy 3.10–3.925 runs
installs and imports cleanly · install 1.9s · import 0.270s · 27MB
25MB installed
● package 25MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
beartype
✓ from beartype import beartype
This is the primary decorator for runtime type-checking of individual functions and methods.
beartype_this_package
✓ from beartype.claw import beartype_this_package
Used to implicitly apply runtime type-checking across all annotated classes, callables, and variable assignments within an entire Python package. Typically called at the top of a package's `__init__.py`.
Is
✓ from beartype.vale import Is
from typing import Annotated
Used in conjunction with `typing.Annotated` (Python >= 3.9) to define custom runtime validators for more complex type-checking scenarios.
This quickstart demonstrates the core usage of the `@beartype` decorator. It shows a function `quote_wiggum` annotated with standard type hints. When called with valid parameters (a list of strings), it executes normally. When called with invalid parameters (a list of bytes), `beartype` intercepts the call and raises a `BeartypeCallHintPepParamException`, providing a clear error message about the type violation.
from beartype import beartype
@beartype
def quote_wiggum(lines: list[str]) -> None:
print('“{}”\n\t— Police Chief Wiggum'.format("\n ".join(lines)))
# Valid call
quote_wiggum(["Okay, folks. Show's over!", "Nothing to see here."])
# Invalid call (will raise BeartypeCallHintPepParamException)
try:
quote_wiggum([b"Oh, my God! A horrible plane crash!"])
except Exception as e:
print(f"Caught expected error: {e.__class__.__name__}: {e}")
Debug
Known issues
gotchaType-checking might be inadvertently disabled when `PYTHONOPTIMIZE=1` or the `-O` flag is used with the Python interpreter in versions prior to `0.22.5`.fixUpgrade to `beartype` 0.22.5 or higher. Alternatively, avoid running Python with `PYTHONOPTIMIZE=1` or the `-O` flag if runtime type-checking is critical for these older versions.
affects: <0.22.5
breakingVersion `0.22.3` introduced a `pyproject.toml` `requires-python` syntax that caused installation failures with `Poetry` and `pipenv` due to their non-standard parsing behavior.fixUpgrade to `beartype` 0.22.4 or higher, which addressed these compatibility issues.
affects: 0.22.3
gotchaSynchronous generator functions decorated with `@beartype` could lose their `inspect.isgeneratorfunction()` property, causing issues with frameworks like Gradio. This was an issue in `0.22.6` and subsequent patches.fixUpgrade to `beartype` 0.22.8 or higher, which restored `inspect.isgeneratorfunction()`-ness for decorated synchronous generator functions.
affects: 0.22.6, 0.22.7
gotchaBeartype has known incompatibilities with `Pydantic` due to `Pydantic`'s non-standard handling of `if TYPE_CHECKING:` blocks and forward references, which can break runtime type-checking. Beartype internally 'blacklists' `Pydantic` to prevent crashes.fixBe aware of potential issues when combining `beartype` with `Pydantic` models. While `beartype` attempts to mitigate conflicts, complex interactions might still arise. Consider using `beartype.door.is_bearable()` or `die_if_unbearable()` for manual checks on Pydantic objects if direct decoration causes problems.
affects: All versions when used with Pydantic
gotchaWhile `beartype` offers O(1) worst-case type-checking performance, users might perceive a minor overhead when compared to entirely untyped Python code. This is primarily due to the inherent cost of Python's function call stack frames and decorator mechanics, not `beartype`'s specific implementation.fixUnderstand that `beartype`'s efficiency refers to the type-checking logic itself, which is highly optimized. The minimal overhead observed is generally a baseline of Python's execution model when decorators are applied, rather than a performance flaw in `beartype`.
affects: All versions
gotchaBeartype raises `BeartypeCallHintParamViolation` when arguments passed to a decorated function do not conform to their declared type hints. This is `beartype`'s intended behavior for enforcing runtime type validation, catching type mismatches such as passing bytes where str is expected.fixEnsure all function arguments strictly adhere to their specified type hints. Review the traceback to identify the specific argument causing the violation and correct the type of the passed value.
affects: All versions
Errors
Common errors & fixes
BeartypeCallHintParamViolation: Function calculate_statistics() parameter data=[1, 'a', 3] violates type hint list[float], as list index 0 item int 1 not instance of float.
This error occurs when a function decorated with `@beartype` receives a parameter whose runtime type does not match the annotated type hint, indicating a type-checking violation at call time.
fixEnsure that the arguments passed to the `@beartype`-decorated function conform to their specified type hints. For the example, `data` should contain only `float` instances.
BeartypeDecorHintForwardRefException: Forward reference "__main__. List[MyCls]" syntactically invalid as module attribute name.
This exception is raised at decoration time when a forward reference (a type hint specified as a string) is syntactically malformed or incorrectly references a type that cannot be resolved by `beartype`.
fixCorrect the stringified forward reference to accurately reflect the type, ensuring it's a valid identifier or path to the target class, often by only stringifying the yet-to-be-defined class (e.g., `List["MyCls"]`) or using `from __future__ import annotations` if applicable.
ImportError: cannot import name 'List' from 'typing'
This error typically occurs in Python 3.9+ when trying to import generic types like `List`, `Dict`, or `Tuple` from the `typing` module, as PEP 585 (Python 3.9+) and PEP 604 (Python 3.10+) made built-in generics (e.g., `list`, `dict`) the standard for type hints. `beartype` often warns about this impending breakage in older Python versions.
fixReplace imports like `from typing import List` with the direct use of built-in generic types (e.g., `list[str]`) or use `from __future__ import annotations` (which effectively enables built-in generics in older Python versions).
ImportError: cannot import name 'ByteString' from 'collections.abc'
This error arises in Python 3.14 and newer versions because `typing.ByteString` (and its corresponding `collections.abc.ByteString`) has been deprecated and subsequently removed.
fixReplace `ByteString` with the built-in `bytes` type, as `bytes` is the appropriate type hint for byte strings.
Audit
Dependencies
No dependency data recorded yet.