Skip to content

Commit

Permalink
Support annotated dataclasses
Browse files Browse the repository at this point in the history
  • Loading branch information
faph committed Nov 17, 2023
1 parent 6afd94c commit 2bf29de
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/py_avro_schema/_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,7 @@ class DataclassSchema(RecordSchema):
@classmethod
def handles_type(cls, py_type: Type) -> bool:
"""Whether this schema class can represent a given Python class"""
py_type = _type_from_annotated(py_type)
return dataclasses.is_dataclass(py_type)

def __init__(self, py_type: Type, namespace: Optional[str] = None, options: Option = Option(0)):
Expand All @@ -846,6 +847,7 @@ def __init__(self, py_type: Type, namespace: Optional[str] = None, options: Opti
:param options: Schema generation options.
"""
super().__init__(py_type, namespace=namespace, options=options)
py_type = _type_from_annotated(py_type)
self.py_fields = dataclasses.fields(py_type)
self.record_fields = [self._record_field(field) for field in self.py_fields]

Expand Down
20 changes: 19 additions & 1 deletion 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 Dict, List, Optional
from typing import Annotated, Dict, List, Optional

import pytest
import typeguard
Expand All @@ -41,6 +41,24 @@ class PyType:
assert_schema(PyType, expected)


def test_class_annotated():
@dataclasses.dataclass
class PyType:
field_a: str

expected = {
"type": "record",
"name": "PyType",
"fields": [
{
"name": "field_a",
"type": "string",
}
],
}
assert_schema(Annotated[PyType, ...], expected)


def test_string_field_mandatory_default():
@dataclasses.dataclass
class PyType:
Expand Down

0 comments on commit 2bf29de

Please sign in to comment.