RussBaz / enforce

Python 3.5+ runtime type checking for integration testing and data validation
542 stars 21 forks source link

Data validation via `typing.Annotated` #79

Open CallumJHays opened 3 years ago

CallumJHays commented 3 years ago

Heya, cool library. I haven't given it a try yet personally, but I've been using typing.Annotated for runtime data validation in a similar way to what you've accomplished here. With your library it might look little something like this:

from typing_extensions import Annotated as An
from enforce import runtime_validation, InRange

@runtime_validation
def test_fn(a: An[int, InRange(0, 100)], b: An[float, InRange(0, 1)]): ...

test_fn(50, 0.5) # works
try:
    test_fn(0.5, 0.5) # TypeError: Expected a to have type <class 'int'> but got <class 'float'>
    test_fn(b=2, a=50) # AssertionError: Argument b=2 not in range [0, 1)
except: ...

Basically the idea is to enable most (if not all) input assertions to be provided by the type of the input rather than asserts in the function body. It's working well for me so far. I've put together a more complete example here: https://gist.github.com/CallumJHays/e4ad98925894a8e1cd7ef57e90fe2807