Skip to content

Commit 569a2fb

Browse files
authored
Merge pull request #584 from yukinarit/fix-init-var-field-attribute
Fix InitVar with field attribute
2 parents 129e030 + c40573a commit 569a2fb

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

serde/core.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -890,15 +890,25 @@ def should_impl_dataclass(cls: type[Any]) -> bool:
890890
if not dataclasses.is_dataclass(cls):
891891
return True
892892

893+
# Checking is_dataclass is not enough in such a case that the class is inherited
894+
# from another dataclass. To do it correctly, check if all fields in __annotations__
895+
# are present as dataclass fields.
893896
annotations = getattr(cls, "__annotations__", {})
894897
if not annotations:
895898
return False
896899

897900
field_names = [field.name for field in dataclass_fields(cls)]
898-
for field_name in annotations:
901+
for field_name, annotation in annotations.items():
902+
# Omit InitVar field because it doesn't appear in dataclass fields.
903+
if is_instance(annotation, dataclasses.InitVar):
904+
continue
905+
# This field in __annotations__ is not a part of dataclass fields.
906+
# This means this class does not implement dataclass directly.
899907
if field_name not in field_names:
900908
return True
901909

910+
# If all of the fields in __annotation__ are present as dataclass fields,
911+
# the class already implemented dataclass, thus returns False.
902912
return False
903913

904914

tests/test_basics.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,3 +1126,12 @@ class Bar(Foo):
11261126

11271127
bar = Bar(a=10, b=20)
11281128
assert bar == serde.from_dict(Bar, serde.to_dict(bar))
1129+
1130+
1131+
def test_init_var_with_field_attribute() -> None:
1132+
@serde.serde
1133+
@dataclasses.dataclass
1134+
class Foo:
1135+
a: int = serde.field(skip=True)
1136+
1137+
assert serde.to_dict(Foo(10)) == {}

0 commit comments

Comments
 (0)