Skip to content

Commit

Permalink
Fix using Optional in tuples
Browse files Browse the repository at this point in the history
  • Loading branch information
Fatal1ty committed Apr 15, 2022
1 parent 9c03c74 commit de8c2f0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions mashumaro/core/meta/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,7 @@ def _pack_tuple(self, fname, value_name, args, parent, metadata) -> str:
parent,
value_name,
metadata=metadata,
could_be_none=True,
)
return f"[{packer} for value in value]"
else:
Expand All @@ -1564,6 +1565,7 @@ def _pack_tuple(self, fname, value_name, args, parent, metadata) -> str:
parent,
f"{value_name}[{arg_idx}]",
metadata=metadata,
could_be_none=True,
)
for arg_idx, arg_type in enumerate(args)
]
Expand All @@ -1581,6 +1583,7 @@ def _unpack_tuple(self, fname, value_name, args, parent, metadata) -> str:
parent,
value_name,
metadata=metadata,
could_be_none=True,
)
return f"tuple([{unpacker} for value in value])"
else:
Expand All @@ -1591,6 +1594,7 @@ def _unpack_tuple(self, fname, value_name, args, parent, metadata) -> str:
parent,
f"{value_name}[{arg_idx}]",
metadata=metadata,
could_be_none=True,
)
for arg_idx, arg_type in enumerate(args)
]
Expand Down
22 changes: 22 additions & 0 deletions tests/test_data_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1234,3 +1234,25 @@ class Config(BaseConfig):
instance = DataClass("a", MyStr("b"))
assert DataClass.from_dict({"x": "str_a", "y": "MyStr_b"}) == instance
assert instance.to_dict() == {"x": "str_a", "y": "MyStr_b"}


def test_tuple_with_optional():
@dataclass
class DataClass(DataClassDictMixin):
x: Tuple[Optional[int], int] = field(default_factory=lambda: (None, 7))

assert DataClass.from_dict({'x': [None, 42]}) == DataClass((None, 42))
assert DataClass((None, 42)).to_dict() == {'x': [None, 42]}
assert DataClass.from_dict({}) == DataClass((None, 7))
assert DataClass().to_dict() == {'x': [None, 7]}


def test_tuple_with_optional_and_ellipsis():
@dataclass
class DataClass(DataClassDictMixin):
x: Tuple[Optional[int], ...] = field(default_factory=lambda: (None, 7))

assert DataClass.from_dict({'x': [None, 42]}) == DataClass((None, 42))
assert DataClass((None, 42)).to_dict() == {'x': [None, 42]}
assert DataClass.from_dict({}) == DataClass((None, 7))
assert DataClass().to_dict() == {'x': [None, 7]}

0 comments on commit de8c2f0

Please sign in to comment.