Runtime type checking decorators for function arguments
pip install philiprehberger-type-guardRuntime type checking decorators for function arguments.
pip install philiprehberger-type-guard
from philiprehberger_type_guard import guard
@guard
def greet(name: str, times: int = 1) -> str:
return name * times
greet("hello", 3) # Works fine
greet(123, 3) # Raises TypeGuardError
@guard
def process(items: list[int], lookup: dict[str, float]):
...
process([1, 2, 3], {"a": 1.0}) # OK
process(["a"], {}) # TypeGuardError
@guard
def flexible(value: int | str | None):
...
flexible(42) # OK
flexible("hi") # OK
flexible(None) # OK
flexible(3.14) # TypeGuardError
For one-off checks outside the @guard decorator, use is_type() (boolean) or assert_type() (raises on mismatch).
from philiprehberger_type_guard import is_type, assert_type
is_type(5, int) # True
is_type("x", int) # False
is_type([1, 2], list[int]) # True
is_type(None, int | None) # True
assert_type(5, int) # returns None
assert_type("x", int) # raises TypeGuardError
assert_type("x", int, name="user_id") # custom name in message
assert_type() honors the global enable() / disable() toggle.
from philiprehberger_type_guard import enable, disable
disable() # Turn off all guards (e.g., in production)
enable() # Turn back on
from philiprehberger_type_guard import TypeGuardError
try:
greet(123, 3)
except TypeGuardError as e:
print(e.param) # "name"
print(e.expected) # "str"
print(e.actual) # <class 'int'>
print(e.value) # 123
| Function / Class | Description |
|---|---|
@guard / @guard(enabled=True) | Decorator for runtime type checking |
is_type(value, expected) | Non-raising check; returns True / False |
assert_type(value, expected, name="value") | Raises TypeGuardError if value does not match expected |
enable() / disable() | Global toggle |
TypeGuardError | Raised on type mismatch (subclass of TypeError) |
pip install -e .
python -m pytest tests/ -v
If you find this project useful: