Created
November 21, 2021 11:00
-
-
Save stereobutter/f057cdd4dba28620b142760311e5102d to your computer and use it in GitHub Desktop.
`cattrs` + `pydantic`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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