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

Represent List[Dict[str, Any]] as JSON logical type #44

Merged
merged 4 commits into from
Sep 12, 2023
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
20 changes: 19 additions & 1 deletion docs/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -214,14 +214,32 @@ Arbitrary Python dictionaries could be serialized as a ``bytes`` Avro schema by
To support JSON serialization as *strings* instead of *bytes*, use :attr:`py_avro_schema.Option.LOGICAL_JSON_STRING`.


:class:`typing.List[typing.Dict[str, typing.Any]]`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. seealso::

For a "normal" Avro ``array`` schema using fully typed Python lists of dictionaries, see :ref:`types::class:`typing.sequence``.


| Avro schema: ``bytes``
| Avro logical type: ``json``

Arbitrary lists of Python dictionaries could be serialized as a ``bytes`` Avro schema by first serializing the data as JSON.
**py-avro-schema** supports this "JSON-in-Avro" approach by adding the **custom** logical type ``json`` to a ``bytes`` schema.

To support JSON serialization as *strings* instead of *bytes*, use :attr:`py_avro_schema.Option.LOGICAL_JSON_STRING`.


:class:`typing.Mapping`
~~~~~~~~~~~~~~~~~~~~~~~

Avro schema: ``map``

This supports other "generic type" versions of :class:`collections.abc.Mapping`, including :class:`typing.Dict`.

Avro ``map`` schemas support **string** keys only. Map values can be any other Python type supported by **py-avro-schema**. For example, ``Dict[str, int]`` is output as:
Avro ``map`` schemas support **string** keys only. Map values can be any other Python type supported by **py-avro-schema**.
For example, ``Dict[str, int]`` is output as:

.. code-block:: json

Expand Down
21 changes: 18 additions & 3 deletions src/py_avro_schema/_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,12 @@ def data(self, names: NamesType) -> JSONObj:


class DictAsJSONSchema(Schema):
"""An Avro string schema representing a Python Dict[str, Any] assuming JSON serialization"""
"""An Avro string schema representing a Python Dict[str, Any] or List[Dict[str, Any]] assuming JSON serialization"""

@classmethod
def handles_type(cls, py_type: Type) -> bool:
"""Whether this schema class can represent a given Python class"""
origin = getattr(py_type, "__origin__", None)
return inspect.isclass(origin) and issubclass(origin, dict) and py_type.__args__ == (str, Any)
return _is_dict_str_any(py_type) or _is_list_dict_str_any(py_type)

def data(self, names: NamesType) -> JSONObj:
"""Return the schema data"""
Expand Down Expand Up @@ -901,3 +900,19 @@ def _doc_for_class(py_type: Type) -> str:
return doc
else:
return ""


def _is_dict_str_any(py_type: Type) -> bool:
"""Return whether a given type is ``Dict[str, Any]``"""
origin = getattr(py_type, "__origin__", None)
return inspect.isclass(origin) and issubclass(origin, dict) and py_type.__args__ == (str, Any)


def _is_list_dict_str_any(py_type: Type) -> bool:
"""Return whether a given type is ``List[Dict[str, Any]]``"""
origin = getattr(py_type, "__origin__", None)
args = getattr(py_type, "__args__", None)
if args:
return inspect.isclass(origin) and issubclass(origin, list) and _is_dict_str_any(args[0])
else:
return False
53 changes: 1 addition & 52 deletions tests/test_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import decimal
import enum
import re
from typing import Any, Dict, List, Optional
from typing import Dict, List, Optional

import pytest

Expand Down Expand Up @@ -603,57 +603,6 @@ class PyType:
assert_schema(PyType, expected, namespace="my_package.my_module")


def test_dict_json_logical_string_field():
@dataclasses.dataclass
class PyType:
field_a: Dict[str, Any] = dataclasses.field(
metadata={"avro_adapter": {"logical_type": "json"}},
default_factory=dict,
)

expected = {
"type": "record",
"name": "PyType",
"fields": [
{
"name": "field_a",
"type": {
"type": "string",
"logicalType": "json",
},
"default": "{}",
}
],
}
options = pas.Option.LOGICAL_JSON_STRING
assert_schema(PyType, expected, options=options)


def test_dict_json_logical_bytes_field():
@dataclasses.dataclass
class PyType:
field_a: Dict[str, Any] = dataclasses.field(
metadata={"avro_adapter": {"logical_type": "json"}},
default_factory=dict,
)

expected = {
"type": "record",
"name": "PyType",
"fields": [
{
"name": "field_a",
"type": {
"type": "bytes",
"logicalType": "json",
},
"default": "{}",
}
],
}
assert_schema(PyType, expected)


def test_decimal_field_default():
@dataclasses.dataclass
class PyType:
Expand Down
39 changes: 39 additions & 0 deletions tests/test_logicals.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import datetime
import uuid
from typing import Any, Dict, List

import py_avro_schema as pas
from py_avro_schema._testing import assert_schema
Expand Down Expand Up @@ -112,3 +113,41 @@ def test_uuid():
"logicalType": "uuid",
}
assert_schema(py_type, expected)


def test_dict_json_logical_string_field():
py_type = Dict[str, Any]
expected = {
"type": "string",
"logicalType": "json",
}
options = pas.Option.LOGICAL_JSON_STRING
assert_schema(py_type, expected, options=options)


def test_dict_json_logical_bytes_field():
py_type = Dict[str, Any]
expected = {
"type": "bytes",
"logicalType": "json",
}
assert_schema(py_type, expected)


def test_list_json_logical_string_field():
py_type = List[Dict[str, Any]]
expected = {
"type": "string",
"logicalType": "json",
}
options = pas.Option.LOGICAL_JSON_STRING
assert_schema(py_type, expected, options=options)


def test_list_json_logical_bytes_field():
py_type = List[Dict[str, Any]]
expected = {
"type": "bytes",
"logicalType": "json",
}
assert_schema(py_type, expected)