Skip to content

Commit 0df2a3a

Browse files
committed
better implementation
1 parent 0512885 commit 0df2a3a

2 files changed

Lines changed: 24 additions & 5 deletions

File tree

src/py_avro_schema/_alias.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import dataclasses
99
from collections import defaultdict
10-
from typing import Annotated, Final, Type, get_args, get_origin
10+
from typing import Annotated, Type, get_args, get_origin
1111

1212
FQN = str
1313
"""Fully qualified name for a Python type"""
@@ -108,10 +108,6 @@ def get_field_aliases_and_actual_type(py_type: Type) -> tuple[list[str] | None,
108108
Check if a type contains an alias metadata via `Alias` or `Aliases` as metadata.
109109
It returns the eventual aliases and the type.
110110
"""
111-
112-
if get_origin(py_type) is Final:
113-
return [], get_args(py_type)[0]
114-
115111
# py_type is not annotated. It can't have aliases
116112
if get_origin(py_type) is not Annotated:
117113
return [], py_type

src/py_avro_schema/_schemas.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
Annotated,
3434
Any,
3535
Dict,
36+
Final,
3637
ForwardRef,
3738
List,
3839
Literal,
@@ -378,6 +379,28 @@ def data(self, names: NamesType) -> JSONType:
378379
return self.literal_value_schema.data(names=names)
379380

380381

382+
@register_schema
383+
class FinalSchema(Schema):
384+
"""An Avro schema for Python ``typing.Final``"""
385+
386+
def __init__(self, py_type: Type, namespace: Optional[str] = None, options: Option = Option(0)):
387+
"""An Avro schema for Python ``typing.Final``"""
388+
super().__init__(py_type, namespace, options)
389+
py_type = _type_from_annotated(py_type)
390+
real_type = get_args(py_type)[0]
391+
self.real_schema = _schema_obj(real_type, namespace=namespace, options=options)
392+
393+
def data(self, names: NamesType) -> JSONType:
394+
"""Return the schema data"""
395+
return self.real_schema.data(names=names)
396+
397+
@classmethod
398+
def handles_type(cls, py_type: Type) -> bool:
399+
"""Whether this schema class can represent a given Python class"""
400+
py_type = _type_from_annotated(py_type)
401+
return get_origin(py_type) is Final
402+
403+
381404
@register_schema
382405
class DictAsJSONSchema(Schema):
383406
"""An Avro string schema representing a Python Dict[str, Any] or List[Dict[str, Any]] assuming JSON serialization"""

0 commit comments

Comments
 (0)