From 99624701a25a98b058c48630fc09248f4ec95315 Mon Sep 17 00:00:00 2001 From: Dmitrii Date: Fri, 4 Aug 2023 11:13:12 +0300 Subject: [PATCH] Add support for dataclasses with InitVar - Ignore init-only variables as they go out of scope when object is encoded (serialized) - Warn on encoding (serialization) of dataclass with InitVar without default value: decoding (deserialization) is impossible! --- chili/typing.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/chili/typing.py b/chili/typing.py index c95d455..684f53b 100644 --- a/chili/typing.py +++ b/chili/typing.py @@ -201,6 +201,13 @@ def create_schema(cls: Type) -> TypeSchema: # ignore class vars as they are not object properties if p_origin and p_origin is ClassVar: continue + + # ignore init-only variables as they go out of scope when object is encoded (serialized) + if type(p_type) is InitVar: + if not name in attributes: + # not optional init-only variables make decoding (deserialization) impossible as they do not persist in encoding (serialization) + warnings.warn(f"Dataclass field '{name}' is InitVar without default value. Decoding is impossible!") + continue if name in attributes: prop_value = attributes[name]