Skip to content

Commit

Permalink
Add supported for Annotated to struct type.
Browse files Browse the repository at this point in the history
Signed-off-by: Pascal Tomecek <[email protected]>
  • Loading branch information
ptomecek committed Oct 15, 2024
1 parent 60dbfd8 commit 415a601
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
3 changes: 3 additions & 0 deletions csp/impl/types/container_type_normalizer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy
import typing
import typing_extensions

import csp.typing
from csp.impl.types.typing_utils import CspTypingUtils, FastList
Expand Down Expand Up @@ -70,6 +71,8 @@ def _convert_containers_to_typing_generic_meta(cls, typ, is_within_container):

@classmethod
def normalized_type_to_actual_python_type(cls, typ, level=0):
if isinstance(typ, typing_extensions._AnnotatedAlias):
typ = CspTypingUtils.get_origin(typ)
if CspTypingUtils.is_generic_container(typ):
if CspTypingUtils.get_origin(typ) is FastList and level == 0:
return [cls.normalized_type_to_actual_python_type(typ.__args__[0], level + 1), True]
Expand Down
17 changes: 17 additions & 0 deletions csp/tests/impl/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import unittest
from datetime import date, datetime, time, timedelta
from typing import Dict, List, Set, Tuple
from typing_extensions import Annotated

import csp
from csp.impl.struct import define_nested_struct, define_struct, defineNestedStruct, defineStruct
Expand Down Expand Up @@ -2943,6 +2944,22 @@ def test_dir(self):
self.assertIn("__metadata__", dir_output)
self.assertEqual(dir_output, sorted(dir_output))

def test_annotations(self):
class StructWithAnnotations(csp.Struct):
b: Annotated[float, "test"]
d: Annotated[Dict[str, Annotated[int, "test_int"]], "test_dict"]
s: str

self.assertEqual(
StructWithAnnotations.metadata(typed=True),
{
"b": Annotated[float, "test"],
"d": Annotated[Dict[str, Annotated[int, "test_int"]], "test_dict"],
"s": str,
},
)
self.assertEqual(StructWithAnnotations.metadata(typed=False), {"b": float, "d": dict, "s": str})


if __name__ == "__main__":
unittest.main()

0 comments on commit 415a601

Please sign in to comment.