|
50 | 50 | root_validator_sig = inspect.Signature() |
51 | 51 |
|
52 | 52 |
|
| 53 | +def _is_optional_typing(type_: Any) -> bool: |
| 54 | + # py version < 3.10 |
| 55 | + # typing.Optional[int] output is: typing.Union[int, None] |
| 56 | + # py version == ^3.9 Optional[int]._name is None |
| 57 | + arg_list = list(get_args(type_)) |
| 58 | + return get_origin(type_) in (typing.Optional, typing.Union) and len(arg_list) == 2 and arg_list[1] is type(None) |
| 59 | + |
| 60 | + |
53 | 61 | class BaseFormatContainer(object): |
54 | 62 | def to_text(self) -> str: |
55 | 63 | raise NotImplementedError |
@@ -192,11 +200,7 @@ def _get_typing_value_code(self, type_: Any, auto_import_type_code: bool = True) |
192 | 200 | # py version < 3.10 |
193 | 201 | # typing.Optional[int] output is: typing.Union[int, None] |
194 | 202 | # py version == ^3.9 Optional[int]._name is None |
195 | | - if ( |
196 | | - get_origin(type_) in (typing.Optional, typing.Union) |
197 | | - and len(arg_list) == 2 |
198 | | - and arg_list[1] is type(None) |
199 | | - ): |
| 203 | + if _is_optional_typing(type_): |
200 | 204 | type_name = "Optional" |
201 | 205 | sub_type_str = f"[{self._get_value_code(arg_list[0])}]" |
202 | 206 | else: |
@@ -383,9 +387,11 @@ def _model_field_handle(self, model: Type[BaseModel], indent: int = 0) -> str: |
383 | 387 | if value_outer_type.__module__ != "builtins": |
384 | 388 | # Get the actual type to check, handling Optional cases |
385 | 389 | type_to_check = value_type |
386 | | - if isinstance(value_outer_type, _GenericAlias) and value_outer_type._name == "Optional": |
| 390 | + if model.__name__ == "WithOptionalEnumMsgEntry": |
| 391 | + print() |
| 392 | + if _is_optional_typing(value_outer_type): |
387 | 393 | type_to_check = get_args(value_outer_type)[0] |
388 | | - |
| 394 | + |
389 | 395 | if inspect.isclass(type_to_check) and issubclass(type_to_check, IntEnum): |
390 | 396 | self._import_set.add("from enum import IntEnum") |
391 | 397 | enum_code: str = self._gen_enum_py_code(type_to_check, indent=indent - self.code_indent) |
|
0 commit comments