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

Check for array-iness in Python de-jsonization #508

Merged
merged 1 commit into from
Jul 6, 2024
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
68 changes: 64 additions & 4 deletions aas_core_codegen/python/jsonization/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,63 @@ def {function_name}(
)


def _generate_is_array_like() -> Stripped:
"""Generate the function to check that the jsonable is an array-like object."""
return Stripped(
f'''\
def _try_to_cast_to_array_like(
{I}jsonable: Jsonable
) -> Optional[Iterable[Any]]:
{I}"""
{I}Try to cast the ``jsonable`` to something like a JSON array.

{I}In particular, we explicitly check that the ``jsonable`` is not a mapping, as we
{I}do not want to mistake dictionaries (*i.e.* de-serialized JSON objects) for lists.

{I}>>> assert _try_to_cast_to_array_like(True) is None

{I}>>> assert _try_to_cast_to_array_like(0) is None

{I}>>> assert _try_to_cast_to_array_like(2.2) is None

{I}>>> assert _try_to_cast_to_array_like("hello") is None

{I}>>> assert _try_to_cast_to_array_like(b"hello") is None

{I}>>> _try_to_cast_to_array_like([1, 2])
{I}[1, 2]

{I}>>> assert _try_to_cast_to_array_like({{"a": 3}}) is None

{I}>>> assert _try_to_cast_to_array_like(collections.OrderedDict()) is None

{I}>>> _try_to_cast_to_array_like(range(1, 2))
{I}range(1, 2)

{I}>>> _try_to_cast_to_array_like((1, 2))
{I}(1, 2)

{I}>>> assert _try_to_cast_to_array_like({{1, 2, 3}}) is None
{I}"""
{I}if (
{II}
{II}not isinstance(jsonable, (str, bytearray, bytes))
{II}and hasattr(jsonable, "__iter__")
{II}and not hasattr(jsonable, "keys")
{II}# NOTE (mristin):
{II}# There is no easy way to check for sets as opposed to sequence except
{II}# for checking for direct inheritance. A sequence also inherits from
{II}# a collection, so both sequences and sets provide ``__contains__`` method.
{II}#
{II}# See: https://docs.python.org/3/library/collections.abc.html
{II}and not isinstance(jsonable, collections.abc.Set)
{I}):
{II}return cast(Iterable[Any], jsonable)

{I}return None'''
)


def _generate_dispatch_map_for_abstract_class(
cls: intermediate.AbstractClass,
) -> Stripped:
Expand Down Expand Up @@ -466,23 +523,24 @@ def ignore(self, jsonable: Jsonable) -> None:

body = Stripped(
f"""\
if not isinstance(jsonable, collections.abc.Iterable):
array_like = _try_to_cast_to_array_like(jsonable)
if array_like is None:
{I}raise DeserializationException(
{II}f"Expected an iterable, but got: {{type(jsonable)}}"
{II}f"Expected something array-like, but got: {{type(jsonable)}}"
{I})

items: List[
{I}{items_type}
] = []
for i, jsonable_item in enumerate(jsonable):
for i, jsonable_item in enumerate(array_like):
{I}try:
{II}item = {parse_function}(
{III}jsonable_item
{II})
{I}except DeserializationException as exception:
{II}exception.path._prepend(
{III}IndexSegment(
{IIII}jsonable,
{IIII}array_like,
{IIII}i
{III})
{II})
Expand Down Expand Up @@ -1047,6 +1105,7 @@ def generate(
import collections.abc
import sys
from typing import (
{I}cast,
{I}Any,
{I}Callable,
{I}Iterable,
Expand Down Expand Up @@ -1205,6 +1264,7 @@ class DeserializationException(Exception):
_generate_float_from_jsonable(),
_generate_str_from_jsonable(),
_generate_bytes_from_jsonable(),
_generate_is_array_like(),
] # type: List[Stripped]

errors = [] # type: List[Error]
Expand Down
Loading
Loading