Open
Description
- cattrs version: 22.2.0
- Python version: 3.10
- Operating System: Windows 10
Description
I have a dataclass that can be instantiated (structured) with a from_dict method, in this way I know all the typings are correct:
from dataclasses import Field, asdict, dataclass, fields
from cattrs import Converter
@dataclass
class MyDataClass:
a: str
b: int
def validate_types(self) -> None:
self.from_dict(asdict(self))
@classmethod
def from_dict(cls, data: dict, converter: Converter = get_converter()):
return converter.structure(data, cls)
It also has a validate_types method that can be run after instantiation
What I Did
I would like to add the validate_types in the post_init:
from dataclasses import Field, asdict, dataclass, fields
from cattrs import Converter
@dataclass
class MyDataClass:
a: str
b: int
def __post_init__(self):
self.validate_types()
def validate_types(self) -> None:
self.from_dict(asdict(self))
@classmethod
def from_dict(cls, data: dict, converter: Converter = get_converter()):
return converter.structure(data, cls)
unfortunately this ends in an infinite loop, because the from_dict generates a new instance of the class and the code goes into the post_init which calls validate_types, which calls from_dict, which creates a new instance of the class which goes into the post_init and on and on.
would it be possible for you to expose a function/method of the converter that only checks if the data can be structured without actually structuring/creating the new instance?