enforce icon indicating copy to clipboard operation
enforce copied to clipboard

Data validation via `typing.Annotated`

Open CallumJHays opened this issue 5 years ago • 0 comments

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

CallumJHays avatar Jan 02 '21 14:01 CallumJHays