Skip to content

Commit e1e24ff

Browse files
committed
feat(protobuf): enhanced type annotations (mypy)
1 parent 74d3ccf commit e1e24ff

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

lagrange/utils/binary/protobuf/models.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,24 @@
66

77
from .coder import Proto, proto_decode, proto_encode
88

9-
_ProtoTypes = Union[str, list, dict, bytes, int, float, bool, "ProtoStruct"]
9+
_ProtoBasicTypes = Union[str, list, dict, bytes, int, float, bool]
10+
_ProtoTypes = Union[_ProtoBasicTypes, "ProtoStruct"]
1011

1112
T = TypeVar("T", str, list, dict, bytes, int, float, bool, "ProtoStruct")
1213
V = TypeVar("V")
1314
NT: TypeAlias = Dict[int, Union[_ProtoTypes, "NT"]]
1415
AMT: TypeAlias = Dict[str, Tuple[Type[_ProtoTypes], "ProtoField"]]
1516
DAMT: TypeAlias = Dict[str, "DelayAnnoType"]
16-
DelayAnnoType = Union[str, type(List[str])]
17+
DelayAnnoType = Union[str, List[str]]
1718
NoneType = type(None)
1819

1920

2021
class ProtoField(Generic[T]):
2122
def __init__(self, tag: int, default: T):
2223
if tag <= 0:
2324
raise ValueError("Tag must be a positive integer")
24-
self._tag = tag
25-
self._default = default
25+
self._tag: int = tag
26+
self._default: T = default
2627

2728
@property
2829
def tag(self) -> int:
@@ -91,11 +92,11 @@ class ProtoStruct:
9192

9293
def __init__(self, *args, **kwargs):
9394
undefined_params: List[str] = []
94-
args = list(args)
95+
args_list = list(args)
9596
self._resolve_annotations(self)
9697
for name, (typ, field) in self._anno_map.items():
9798
if args:
98-
self._set_attr(name, typ, args.pop(0))
99+
self._set_attr(name, typ, args_list.pop(0))
99100
elif name in kwargs:
100101
self._set_attr(name, typ, kwargs.pop(name))
101102
else:
@@ -104,9 +105,7 @@ def __init__(self, *args, **kwargs):
104105
else:
105106
undefined_params.append(name)
106107
if undefined_params:
107-
raise AttributeError(
108-
"Undefined parameters in '{}': {}".format(self, undefined_params)
109-
)
108+
raise AttributeError(f"Undefined parameters in {self}: {undefined_params}")
110109

111110
def __init_subclass__(cls, **kwargs):
112111
cls._proto_debug = kwargs.pop("debug") if "debug" in kwargs else False
@@ -125,9 +124,7 @@ def _set_attr(self, name: str, data_typ: Type[V], value: V) -> None:
125124
if isinstance(data_typ, GenericAlias): # force ignore
126125
pass
127126
elif not isinstance(value, data_typ) and value is not None:
128-
raise TypeError(
129-
"'{}' is not a instance of type '{}'".format(value, data_typ)
130-
)
127+
raise TypeError("{value} is not a instance of type {data_typ}")
131128
setattr(self, name, value)
132129

133130
@classmethod
@@ -191,13 +188,13 @@ def _get_stored_mapping(self) -> Dict[str, NT]:
191188
def _resolve_annotations(arg: Union[Type["ProtoStruct"], "ProtoStruct"]) -> None:
192189
for k, v in arg._delay_anno_map.copy().items():
193190
module = importlib.import_module(arg.__module__)
194-
if hasattr(v, "__origin__"): # resolve GenericAlias, such as list[str]
195-
arg._anno_map[k] = (v.__origin__[module.__getattribute__(v.__args__[0])], arg._anno_map[k][1])
196-
else:
197-
arg._anno_map[k] = (module.__getattribute__(v), arg._anno_map[k][1])
191+
if isinstance(v, GenericAlias): # resolve GenericAlias, such as list[str]
192+
arg._anno_map[k] = (v.__origin__[getattr(module, v.__args__[0])], arg._anno_map[k][1])
193+
if isinstance(v, str):
194+
arg._anno_map[k] = (getattr(module, v), arg._anno_map[k][1])
198195
arg._delay_anno_map.pop(k)
199196

200-
def _encode(self, v: _ProtoTypes) -> NT:
197+
def _encode(self, v: _ProtoTypes) -> _ProtoBasicTypes:
201198
if isinstance(v, ProtoStruct):
202199
v = v.encode()
203200
return v
@@ -266,4 +263,3 @@ def decode(cls, data: bytes) -> Self:
266263

267264
return cls(**kwargs)
268265

269-

0 commit comments

Comments
 (0)