python-enforce-typing icon indicating copy to clipboard operation
python-enforce-typing copied to clipboard

coerce flag

Open mkujbus opened this issue 4 years ago • 1 comments

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.

mkujbus avatar Nov 22 '21 13:11 mkujbus

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

gpalasti avatar Dec 17 '21 14:12 gpalasti