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
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 |
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: