Sub class validator behaviour loses type.
See original GitHub issueThere’s some non-obvious behaviour that loses types in pydantic in the following case.
import pydantic
class IntSub(int):
pass
class IntConf(pydantic.BaseModel):
count: IntSub
c = IntSub(42)
x = IntConf(count=c)
assert type(x.count) is IntSub
This is because find_validators() checks whether count is a subclass of int and if it is returns a (int, number_size_validator) pair of validators. So upon creation x.count is set to int©.
This could be fixed by replacing the int() validator with the following:
def new_int_validator(x):
try:
int(x)
except ValueError:
raise SomeDescriptiveError("blah blah")
return x
This is more strongly typed and since we appear to be caring about typing if we’re using pydantic, better … I believe. But this is a breaking change since things like IntSub(3.14) and IntSub(“2”) will stop working.
Same goes for float subtypes … I assume.
An alternative is to require a cast constructor for subclasses and use that to check the type instead, e.g. consider what pydantic does without the explicit c=IntSub(42) step above. So perhaps a better check is that the input is already of the expected type… if not try a cast constructor, if that fails we tried.
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (3 by maintainers)
Humm, I see the problem, but I definitely want
3.14
and"2"
to work with int fields.It looks like it’s not properly documented by the solution is to use
get_validators
like constr does.You’ll want something like
Let me know if that works.
fix via #157