connor-makowski / type_enforced

A pure python type enforcer for annotations. Enforce types in python functions and methods.
MIT License
45 stars 2 forks source link

Adding ability to enforce with constraints #37

Closed kakaday22 closed 7 months ago

kakaday22 commented 7 months ago

This PR has enhances the Enforcer decorator to enforce parameters with constraints Relates to Issue: https://github.com/connor-makowski/type_enforced/issues/36

Examples:

from type_enforced import Enforcer
from type_enforced.type import Constraint
from typing import Annotated

PositiveInt = Annotated[int, Constraint(ge=0)]

@Enforcer
def func(value: PositiveInt):
    return True

func(1)  # -> Valid
func(-1)  # Throws ConstraintError as per annotation we are expecting >= 0 (new behavior)
func("foo")  # Throws TypeError as annotation is set to integer (existing behavior)
from type_enforced import Enforcer
from type_enforced.type import Constraint
from typing import Annotated

StoppedStrs = Annotated[str, Constraint(pattern=r".*stopped.*")]

@Enforcer
def func(value: StoppedStrs):
    return True

func("stopped instance")  # -> Valid
func("started instance")  # Throws ConstraintError as per annotation we are expecting strings to match pattern
func(1)  # Throws TypeError as annotation is set to integer
connor-makowski commented 7 months ago

Thanks for the work here. This is great. I am closing this out and merging into a dev branch for 1.5.0 to modify and change from there.