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 tuple passthrough to PassThroughOptions #255

Merged
merged 2 commits into from
Nov 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions apischema/serialization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion examples/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)})
Expand Down