Beartype
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.
Warnings
- gotcha Type-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`.
- breaking Version `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.
- gotcha Synchronous 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.
- gotcha Beartype 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.
- gotcha While `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.
Install
-
pip install beartype
Imports
- beartype
from beartype import beartype
- beartype_this_package
from beartype.claw import beartype_this_package
- Is
from beartype.vale import Is from typing import Annotated
Quickstart
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}")