Type Enforced
Type-enforced is a pure Python library that provides runtime type enforcement for Python type annotations. It uses a decorator-based approach to validate type hints in functions, methods, and classes, ensuring data integrity at runtime. The library is currently at version 2.3.0 and maintains an active release cadence with frequent updates and bug fixes.
Warnings
- breaking Version 2.0.0 introduced significant breaking changes. Python 3.10 support was dropped (requiring >=3.11). List-based union types (e.g., `[int, float]`) are no longer supported; use `int | float` or `typing.Union[int, float]` instead. Dictionary type hints now strictly require both key and value types (e.g., `dict[str, int]`).
- breaking Version 1.10.0 dropped support for Python 3.9. Users on Python 3.9 or older must use `type_enforced<=1.9.0` for full compatibility.
- gotcha When using forward references in type annotations (e.g., `def my_func(arg: 'MyClass')`), the type_enforced library lazily evaluates these types on the first call. Ensure the referenced class/type is defined and resolvable in the scope *before* the first execution of the decorated function/method to avoid resolution issues.
- gotcha By default since version 2.1.0, `type_enforced` checks for subclasses when validating types. If you define `arg: ParentClass`, passing an instance of `ChildClass(ParentClass)` will pass validation. If strict exact type matching is required, this default behavior might be unexpected.
- gotcha The `@Enforcer` decorator has `enabled` and `strict` parameters (both `True` by default). Setting `enabled=False` disables all type checking for that function/class. Setting `strict=False` will print a warning to the console on type mismatch instead of raising a `TypeError`.
Install
-
pip install type-enforced
Imports
- Enforcer
from type_enforced import Enforcer
Quickstart
from type_enforced import Enforcer
@Enforcer()
def greet(name: str, age: int) -> str:
return f"Hello, {name}! You are {age} years old."
print(greet("Alice", 30))
try:
greet("Bob", "twenty") # This will raise a TypeError
except TypeError as e:
print(f"Caught expected error: {e}")