Skip to content

Commit 488781f

Browse files
committed
Fix, fix py3.9 not support optional enum
1 parent c0f772d commit 488781f

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

protobuf_to_pydantic/gen_code.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@
5050
root_validator_sig = inspect.Signature()
5151

5252

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+
5361
class BaseFormatContainer(object):
5462
def to_text(self) -> str:
5563
raise NotImplementedError
@@ -192,11 +200,7 @@ def _get_typing_value_code(self, type_: Any, auto_import_type_code: bool = True)
192200
# py version < 3.10
193201
# typing.Optional[int] output is: typing.Union[int, None]
194202
# 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_):
200204
type_name = "Optional"
201205
sub_type_str = f"[{self._get_value_code(arg_list[0])}]"
202206
else:
@@ -383,9 +387,11 @@ def _model_field_handle(self, model: Type[BaseModel], indent: int = 0) -> str:
383387
if value_outer_type.__module__ != "builtins":
384388
# Get the actual type to check, handling Optional cases
385389
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):
387393
type_to_check = get_args(value_outer_type)[0]
388-
394+
389395
if inspect.isclass(type_to_check) and issubclass(type_to_check, IntEnum):
390396
self._import_set.add("from enum import IntEnum")
391397
enum_code: str = self._gen_enum_py_code(type_to_check, indent=indent - self.code_indent)

0 commit comments

Comments
 (0)