From e24fe2743b8a961e9df3600ae420d5f8a42c5fb4 Mon Sep 17 00:00:00 2001 From: Joseph Perez Date: Fri, 26 Nov 2021 21:39:26 +0100 Subject: [PATCH 1/2] Add tuple passthrough to PassThroughOptions --- apischema/serialization/__init__.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/apischema/serialization/__init__.py b/apischema/serialization/__init__.py index 73b7058b..30ce341c 100644 --- a/apischema/serialization/__init__.py +++ b/apischema/serialization/__init__.py @@ -84,6 +84,7 @@ class PassThroughOptions: any: bool = False collections: bool = False enums: bool = False + tuple: bool = False types: Union[Collection[AnyType], Callable[[AnyType], bool]] = () def __post_init__(self): @@ -198,9 +199,13 @@ def method(obj: Any) -> Any: # using map is faster than comprehension return list(map(serialize_value, obj)) - elif issubclass(cls, (list, tuple)) or ( - self.pass_through_options.collections - and not issubclass(cls, collections.abc.Set) + elif ( + issubclass(cls, list) + or (issubclass(cls, tuple) and self.pass_through_options.tuple) + or ( + self.pass_through_options.collections + and not issubclass(cls, collections.abc.Set) + ) ): method = identity else: @@ -354,7 +359,7 @@ def subprimitive(self, cls: Type, superclass: Type) -> SerializationMethod: def tuple(self, types: Sequence[AnyType]) -> SerializationMethod: elt_serializers = list(enumerate(map(self.visit, types))) if all(method is identity for _, method in elt_serializers): - return identity + return identity if self.pass_through_options.tuple else list # type: ignore def method(obj: Any) -> Any: return [serialize_elt(obj[i]) for i, serialize_elt in elt_serializers] From 728afda199e8b70454a0f72bb902374edd702704 Mon Sep 17 00:00:00 2001 From: Joseph Perez Date: Fri, 26 Nov 2021 21:59:23 +0100 Subject: [PATCH 2/2] Fix test --- examples/serialization.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/serialization.py b/examples/serialization.py index a62b0dc3..1656467d 100644 --- a/examples/serialization.py +++ b/examples/serialization.py @@ -10,7 +10,7 @@ class Foo: assert serialize(Foo, Foo("baz")) == {"bar": "baz"} -assert serialize(tuple[int, int], (0, 1)) == (0, 1) +assert serialize(tuple[int, int], (0, 1)) == [0, 1] assert ( serialize(Any, {"key": ("value", 42)}) == serialize({"key": ("value", 42)})