matchawine / python-enforce-typing

An easy to use decorator to enforce static typing for function and dataclasses.
GNU General Public License v3.0
43 stars 6 forks source link

coerce flag #9

Open mkujbus opened 2 years ago

mkujbus commented 2 years ago

Hi All,

Can we add a coerce=True boolean flag to the enforce_typing decorator, so that if coercable types are found, we dont fail?

For example assume the variable x is typed to be float and we inject a value of 3 (int). We could coerce an int to a float, hence we should continue with the execution.

This would be very helpful as a decimal - float conversion setup also.

gpalasti commented 2 years ago

It would be even better if coerce could be callable, not just a boolean

Lets assume that we have a class called Class1

` def coerceClass1(x: Union[Class1, dict]) -> Class1: if isinstance(x, dict): return Class1(**x) return x

@dataclass class Class2: foo: int klass1: Union[Class1, dict] = field(default=None, compare=False, hash=False, coerce=coerceClass1) ` Right now i can implement this using __post_init__