Skip to content

Commit cf07b83

Browse files
authored
Implementing opaque fields (#8)
1 parent 583ddea commit cf07b83

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

src/py_avro_schema/_alias.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ class Aliases:
2929
aliases: list[str]
3030

3131

32+
class Opaque:
33+
"""
34+
This is a marker for complex Avro fields (e.g., maps) that are serialized to a simple string.
35+
"""
36+
37+
pass
38+
39+
3240
def get_fully_qualified_name(py_type: type) -> str:
3341
"""Returns the fully qualified name for a Python type"""
3442
module = getattr(py_type, "__module__", None)
@@ -107,6 +115,11 @@ def get_field_aliases_and_actual_type(py_type: Type) -> tuple[list[str] | None,
107115
args = get_args(py_type)
108116
actual_type, annotation = args[0], args[1]
109117

118+
# When a field is annotated with the Opaque class, we return bytes as type.
119+
# The object serializer is responsible for dumping the entire attribute as a JSON string
120+
if isinstance(annotation, type) and issubclass(annotation, Opaque):
121+
return [], str
122+
110123
# Annotated type but not an alias. We do nothing.
111124
if type(annotation) not in (Alias, Aliases):
112125
return [], py_type

tests/test_plain_class.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import pytest
1616

1717
import py_avro_schema
18-
from py_avro_schema._alias import Alias, register_type_aliases
18+
from py_avro_schema._alias import Alias, Opaque, register_type_aliases
1919
from py_avro_schema._testing import assert_schema
2020

2121

@@ -130,3 +130,16 @@ def __init__(
130130
),
131131
):
132132
assert_schema(PyType, {})
133+
134+
135+
def test_opaque_field():
136+
class Details:
137+
name: str
138+
surname: str
139+
age: int
140+
141+
class PyType:
142+
details: Annotated[Details, Opaque]
143+
144+
expected = {"fields": [{"name": "details", "type": "string"}], "name": "PyType", "type": "record"}
145+
assert_schema(PyType, expected)

0 commit comments

Comments
 (0)