Skip to content

Commit fd4ec45

Browse files
authored
Extend as JSON schema to include list[Any] (#12)
1 parent 737be58 commit fd4ec45

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

src/py_avro_schema/_schemas.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -405,13 +405,16 @@ def handles_type(cls, py_type: Type) -> bool:
405405

406406

407407
@register_schema
408-
class DictAsJSONSchema(Schema):
409-
"""An Avro string schema representing a Python Dict[str, Any] or List[Dict[str, Any]] assuming JSON serialization"""
408+
class TypeAsJSONSchema(Schema):
409+
"""
410+
An Avro string schema representing a Python Dict[str, Any], List[Dict[str, Any]] or List[Any] assuming
411+
JSON serialization
412+
"""
410413

411414
@classmethod
412415
def handles_type(cls, py_type: Type) -> bool:
413416
"""Whether this schema class can represent a given Python class"""
414-
return _is_dict_str_any(py_type) or _is_list_dict_str_any(py_type)
417+
return is_logically_json(py_type)
415418

416419
def data(self, names: NamesType) -> JSONObj:
417420
"""Return the schema data"""
@@ -1280,6 +1283,17 @@ def _is_list_dict_str_any(py_type: Type) -> bool:
12801283
return False
12811284

12821285

1286+
def _is_list_any(py_type: Type) -> bool:
1287+
"""Return whether a given type is ``List[Any]``"""
1288+
origin = get_origin(py_type)
1289+
return inspect.isclass(origin) and issubclass(origin, list) and get_args(py_type) == (Any,)
1290+
1291+
1292+
def is_logically_json(py_type: Type) -> bool:
1293+
"""Returns whether a given type is logically a JSON and can be serialized as such"""
1294+
return _is_list_any(py_type) or _is_list_dict_str_any(py_type) or _is_dict_str_any(py_type)
1295+
1296+
12831297
def _is_class(py_type: Any, of_types: Union[Type, Tuple[Type, ...]], include_subclasses: bool = True) -> bool:
12841298
"""Return whether the given type is a (sub) class of a type or types"""
12851299
py_type = _type_from_annotated(py_type)

tests/test_logicals.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,3 +285,9 @@ def test_list_json_logical_bytes_field():
285285
"logicalType": "json",
286286
}
287287
assert_schema(py_type, expected)
288+
289+
290+
def test_list_json_logical_list_any():
291+
py_type = List[Any]
292+
expected = {"type": "bytes", "logicalType": "json"}
293+
assert_schema(py_type, expected)

0 commit comments

Comments
 (0)