Skip to content

Commit 7452ec2

Browse files
authored
Fix bug (exposed by lovasoa#159) in serialization of optional union types (lovasoa#160)
* Fix bug exposed by lovasoa#159 with serialization of optional union types * Update CHANGELOG.md * v8.5.2
1 parent 248fe32 commit 7452ec2

File tree

4 files changed

+21
-3
lines changed

4 files changed

+21
-3
lines changed

CHANGELOG.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
# marshmallow\_dataclass change log
22

3+
## v8.5.2
4+
5+
- Fix spurious `TypeError` when serializing `Optional` union types with `required=True`
6+
([#160](https://github.com/lovasoa/marshmallow_dataclass/pull/160))
7+
38
## v8.5.1
49

5-
- Allow setting required=True on fields of type Optional (#159)
10+
- Allow setting required=True on fields of type Optional
11+
([#159](https://github.com/lovasoa/marshmallow_dataclass/pull/159))
612

713
## v8.5.0
814
- Fix `default` warning coming from marshmallow. Bump minimal marshmallow version requirement to 3.13. [See #157](https://github.com/lovasoa/marshmallow_dataclass/issues/157).

marshmallow_dataclass/union_field.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def _bind_to_schema(self, field_name: str, schema: Schema) -> None:
3636

3737
def _serialize(self, value: Any, attr: str, obj, **kwargs) -> Any:
3838
errors = []
39-
if value is None and not self.required:
39+
if value is None:
4040
return value
4141
for typ, field in self.union_fields:
4242
try:

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from setuptools import setup, find_packages
22

3-
VERSION = "8.5.1"
3+
VERSION = "8.5.2"
44

55
CLASSIFIERS = [
66
"Development Status :: 4 - Beta",

tests/test_union.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from dataclasses import field
12
import unittest
23
from typing import List, Optional, Union, Dict
34

@@ -154,3 +155,14 @@ class Dclass:
154155

155156
for data_in in [{"value": None}, {}]:
156157
self.assertEqual(schema.dump(schema.load(data_in)), {"value": None})
158+
159+
def test_required_optional_simple_union(self):
160+
@dataclass
161+
class Dclass:
162+
value: Optional[Union[int, str]] = field(metadata={"required": True})
163+
164+
schema = Dclass.Schema()
165+
166+
for value in None, 42, "strvar":
167+
self.assertEqual(schema.dump(Dclass(value=value)), {"value": value})
168+
self.assertEqual(schema.load({"value": value}), Dclass(value=value))

0 commit comments

Comments
 (0)