Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Python 3.10 Union syntax #189

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions jsons/_lizers_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
This module contains functionality for setting and getting serializers and
deserializers.
"""
import types
from typing import Optional, Dict, Sequence, Union

from jsons._cache import cached
Expand Down Expand Up @@ -156,4 +157,7 @@ def _get_parents(cls: type, lizers: list) -> list:
parents.append(cls_)
except (TypeError, AttributeError):
pass # Some types do not support `issubclass` (e.g. Union).
if not parents and isinstance(naked_cls, types.UnionType) and \
Union in lizers:
parents = [Union]
return parents
33 changes: 33 additions & 0 deletions tests/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,27 @@ def __init__(self, y: int):
with self.assertRaises(SerializationError):
jsons.dump(A(1), Union[B], strict=True)

def test_dump_union_syntax(self):
class A:
def __init__(self, x: int | float):
self.x = x

dumped = jsons.dump(A(1))
expected = {'x': 1}
self.assertDictEqual(expected, dumped)

dumped2 = jsons.dump(A(1), strict=True)
expected2 = {'x': 1}
self.assertDictEqual(expected2, dumped2)

dumped = jsons.dump(A(2.0))
expected = {'x': 2.0}
self.assertDictEqual(expected, dumped)

dumped2 = jsons.dump(A(2.0), strict=True)
expected2 = {'x': 2.0}
self.assertDictEqual(expected2, dumped2)

def test_fail(self):
with self.assertRaises(SerializationError) as err:
jsons.dump('nope', Union[int, float])
Expand Down Expand Up @@ -126,6 +147,18 @@ def __init__(self, x: Union[datetime.datetime, A]):
with self.assertRaises(DeserializationError):
jsons.load({'x': 'no match in the union'}, C).x

def test_load_union_syntax(self):
class A:
def __init__(self, x: int | float):
self.x = x

self.assertEqual(1, jsons.load({'x': 1}, A).x)
self.assertEqual(2.0, jsons.load({'x': 2.0}, A).x)

# Test Union with invalid value.
with self.assertRaises(DeserializationError):
jsons.load({'x': 'no match in the union'}, A).x

def test_load_none(self):
class C:
def __init__(self, x: int, y: Optional[int]):
Expand Down