Skip to content

Instantly share code, notes, and snippets.

@samuelcolvin
Created December 20, 2019 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelcolvin/714e75a74284696204de390a121b0da0 to your computer and use it in GitHub Desktop.
Save samuelcolvin/714e75a74284696204de390a121b0da0 to your computer and use it in GitHub Desktop.
partial implementation of a pydantic validator to enforce JSON types
from datetime import datetime
from typing import Dict
from uuid import UUID
from pydantic import BaseModel, validator
from devtools import debug
NoneType = type(None)
json_types = {int, float, bool, NoneType}
class Model(BaseModel):
a: UUID
b: datetime
c: int
d: Dict[str, int]
@validator('*', pre=True, each_item=True)
def json_types_strict(cls, v, field):
# doesn't yet deal with list and dict
if field.type_ in json_types:
assert type(v) == field.type_, f'wrong type, got {type(v).__name__}, expected {field.type_.__name__}'
# if field.type_ is datetime ...
return v
m = Model(a='4c4eb481-7576-4a34-b515-ee8cdd7697db', b=1234567890, c=123, d={'x': 1})
debug(m)
"""
test.py:27 <module>
m: Model(
a=UUID('4c4eb481-7576-4a34-b515-ee8cdd7697db'),
b=datetime.datetime(2009, 2, 13, 23, 31, 30, tzinfo=datetime.timezone.utc),
c=123,
d={'x': 1},
) (Model)
"""
m = Model(a='4c4eb481-7576-4a34-b515-ee8cdd7697db', b=1234567890, c=123.2, d={'x': 1})
"""
pydantic.error_wrappers.ValidationError: 1 validation error for Model
c
wrong type, got float, expected int (type=assertion_error)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment