Skip to content

Instantly share code, notes, and snippets.

@stereobutter
Created November 21, 2021 11:00
Show Gist options
  • Save stereobutter/f057cdd4dba28620b142760311e5102d to your computer and use it in GitHub Desktop.
Save stereobutter/f057cdd4dba28620b142760311e5102d to your computer and use it in GitHub Desktop.
`cattrs` + `pydantic`
import cattr
class Cattrs:
"""A pydantic compatible field class that uses `cattrs` to structure data """
def __hash__(self):
return hash((type(self), self._model))
def __eq__(self, other):
return hash(self) == hash(other)
def __init__(self, model):
self._model = model
def __class_getitem__(cls, item):
return cls(item)
def __get_validators__(self):
yield self._validate
def _validate(self, value):
if isinstance(value, self._model):
return value
return cattr.structure(value, self._model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment