| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | """ |
| 8 | Type-safe data interchange for Python data classes. |
| 9 | |
| 10 | :see: https://github.com/hunyadi/strong_typing |
| 11 | """ |
| 12 | |
| 13 | import typing |
| 14 | from typing import Any, Literal, Optional, Tuple, Union |
| 15 | |
| 16 | from .auxiliary import _auxiliary_types |
| 17 | from .inspection import ( |
| 18 | is_generic_dict, |
| 19 | is_generic_list, |
| 20 | is_type_optional, |
| 21 | is_type_union, |
| 22 | TypeLike, |
| 23 | unwrap_generic_dict, |
| 24 | unwrap_generic_list, |
| 25 | unwrap_optional_type, |
| 26 | unwrap_union_types, |
| 27 | ) |
| 28 | |
| 29 | |
| 30 | class TypeFormatter: |
| 31 | """ |
| 32 | Type formatter. |
| 33 | |
| 34 | :param use_union_operator: Whether to emit union types as `X | Y` as per PEP 604. |
| 35 | """ |
| 36 | |
| 37 | use_union_operator: bool |
| 38 | |
| 39 | def __init__(self, use_union_operator: bool = False) -> None: |
| 40 | self.use_union_operator = use_union_operator |
| 41 | |
| 42 | def union_to_str(self, data_type_args: Tuple[TypeLike, ...]) -> str: |
| 43 | if self.use_union_operator: |
| 44 | return " | ".join(self.python_type_to_str(t) for t in data_type_args) |
| 45 | else: |
| 46 | if len(data_type_args) == 2 and type(None) in data_type_args: |
| 47 | # Optional[T] is represented as Union[T, None] |
| 48 | origin_name = "Optional" |
| 49 | data_type_args = tuple(t for t in data_type_args if t is not type(None)) |
| 50 | else: |
| 51 | origin_name = "Union" |
| 52 | |
| 53 | args = ", ".join(self.python_type_to_str(t) for t in data_type_args) |
| 54 | return f"{origin_name}[{args}]" |
| 55 | |
| 56 | def plain_type_to_str(self, data_type: TypeLike) -> str: |
| 57 | "Returns the string representation of a Python type without metadata." |
| 58 | |
| 59 | # return forward references as the annotation string |
| 60 | if isinstance(data_type, typing.ForwardRef): |
| 61 | fwd: typing.ForwardRef = data_type |
| 62 | return fwd.__forward_arg__ |
| 63 | elif isinstance(data_type, str): |
| 64 | return data_type |
| 65 | |
| 66 | origin = typing.get_origin(data_type) |
| 67 | if origin is not None: |
| 68 | data_type_args = typing.get_args(data_type) |
| 69 | |
| 70 | if origin is dict: # Dict[T] |
| 71 | origin_name = "Dict" |
| 72 | elif origin is list: # List[T] |
| 73 | origin_name = "List" |
| 74 | elif origin is set: # Set[T] |
| 75 | origin_name = "Set" |
| 76 | elif origin is Union: |
| 77 | return self.union_to_str(data_type_args) |
| 78 | elif origin is Literal: |
| 79 | args = ", ".join(repr(arg) for arg in data_type_args) |
| 80 | return f"Literal[{args}]" |
| 81 | else: |
| 82 | origin_name = origin.__name__ |
| 83 | |
| 84 | args = ", ".join(self.python_type_to_str(t) for t in data_type_args) |
| 85 | return f"{origin_name}[{args}]" |
| 86 | |
| 87 | return data_type.__name__ |
| 88 | |
| 89 | def python_type_to_str(self, data_type: TypeLike) -> str: |
| 90 | "Returns the string representation of a Python type." |
| 91 | |
| 92 | if data_type is type(None): |
| 93 | return "None" |
| 94 | |
| 95 | # use compact name for alias types |
| 96 | name = _auxiliary_types.get(data_type) |
| 97 | if name is not None: |
| 98 | return name |
| 99 | |
| 100 | metadata = getattr(data_type, "__metadata__", None) |
| 101 | if metadata is not None: |
| 102 | # type is Annotated[T, ...] |
| 103 | metatuple: Tuple[Any, ...] = metadata |
| 104 | arg = typing.get_args(data_type)[0] |
| 105 | |
| 106 | # check for auxiliary types with user-defined annotations |
| 107 | metaset = set(metatuple) |
| 108 | for auxiliary_type, auxiliary_name in _auxiliary_types.items(): |
| 109 | auxiliary_arg = typing.get_args(auxiliary_type)[0] |
| 110 | if arg is not auxiliary_arg: |
| 111 | continue |
| 112 | |
| 113 | auxiliary_metatuple: Optional[Tuple[Any, ...]] = getattr( |
| 114 | auxiliary_type, "__metadata__", None |
| 115 | ) |
| 116 | if auxiliary_metatuple is None: |
| 117 | continue |
| 118 | |
| 119 | if metaset.issuperset(auxiliary_metatuple): |
| 120 | # type is an auxiliary type with extra annotations |
| 121 | auxiliary_args = ", ".join( |
| 122 | repr(m) for m in metatuple if m not in auxiliary_metatuple |
| 123 | ) |
| 124 | return f"Annotated[{auxiliary_name}, {auxiliary_args}]" |
| 125 | |
| 126 | # type is an annotated type |
| 127 | args = ", ".join(repr(m) for m in metatuple) |
| 128 | return f"Annotated[{self.plain_type_to_str(arg)}, {args}]" |
| 129 | else: |
| 130 | # type is a regular type |
| 131 | return self.plain_type_to_str(data_type) |
| 132 | |
| 133 | |
| 134 | def python_type_to_str(data_type: TypeLike, use_union_operator: bool = False) -> str: |
| 135 | """ |
| 136 | Returns the string representation of a Python type. |
| 137 | |
| 138 | :param use_union_operator: Whether to emit union types as `X | Y` as per PEP 604. |
| 139 | """ |
| 140 | |
| 141 | fmt = TypeFormatter(use_union_operator) |
| 142 | return fmt.python_type_to_str(data_type) |
| 143 | |
| 144 | |
| 145 | def python_type_to_name(data_type: TypeLike, force: bool = False) -> str: |
| 146 | """ |
| 147 | Returns the short name of a Python type. |
| 148 | |
| 149 | :param force: Whether to produce a name for composite types such as generics. |
| 150 | """ |
| 151 | |
| 152 | # use compact name for alias types |
| 153 | name = _auxiliary_types.get(data_type) |
| 154 | if name is not None: |
| 155 | return name |
| 156 | |
| 157 | # unwrap annotated types |
| 158 | metadata = getattr(data_type, "__metadata__", None) |
| 159 | if metadata is not None: |
| 160 | # type is Annotated[T, ...] |
| 161 | arg = typing.get_args(data_type)[0] |
| 162 | return python_type_to_name(arg) |
| 163 | |
| 164 | if force: |
| 165 | # generic types |
| 166 | if is_type_optional(data_type, strict=True): |
| 167 | inner_name = python_type_to_name(unwrap_optional_type(data_type)) |
| 168 | return f"Optional__{inner_name}" |
| 169 | elif is_generic_list(data_type): |
| 170 | item_name = python_type_to_name(unwrap_generic_list(data_type)) |
| 171 | return f"List__{item_name}" |
| 172 | elif is_generic_dict(data_type): |
| 173 | key_type, value_type = unwrap_generic_dict(data_type) |
| 174 | key_name = python_type_to_name(key_type) |
| 175 | value_name = python_type_to_name(value_type) |
| 176 | return f"Dict__{key_name}__{value_name}" |
| 177 | elif is_type_union(data_type): |
| 178 | member_types = unwrap_union_types(data_type) |
| 179 | member_names = "__".join( |
| 180 | python_type_to_name(member_type) for member_type in member_types |
| 181 | ) |
| 182 | return f"Union__{member_names}" |
| 183 | |
| 184 | # named system or user-defined type |
| 185 | if hasattr(data_type, "__name__") and not typing.get_args(data_type): |
| 186 | return data_type.__name__ |
| 187 | |
| 188 | raise TypeError(f"cannot assign a simple name to type: {data_type}") |