Skip to content

Commit 80025f9

Browse files
committed
Improve the typing of the example in BaseApiClient
The `mypy-protobuf` plugin generates a `XxxAsyncStub` class for each service, which have proper type information to be used with async. This still needs some hacks (type ignore) to make it work, but it's better than using the normal stubs and having to cast on each call. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 242200e commit 80025f9

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/frequenz/client/base/client.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,9 @@ class BaseApiClient(abc.ABC, Generic[StubT]):
4242
from frequenz.client.base.streaming import GrpcStreamBroadcaster
4343
from frequenz.channels import Receiver
4444
45-
# These classes are normally generated by protoc
45+
# These classes are normally generated by protoc, please use mypy-protobuf to
46+
# get proper type checking and the XxxAsyncStub class (only for typing)
47+
# generated.
4648
class ExampleRequest:
4749
int_value: int
4850
str_value: str
@@ -51,6 +53,9 @@ class ExampleResponse:
5153
float_value: float
5254
5355
class ExampleStub:
56+
...
57+
58+
class ExampleAsyncStub:
5459
async def example_method(
5560
self,
5661
request: ExampleRequest # pylint: disable=unused-argument
@@ -65,10 +70,14 @@ class ExampleResponseWrapper:
6570
def __init__(self, response: ExampleResponse):
6671
self.transformed_value = f"{response.float_value:.2f}"
6772
68-
class MyApiClient(BaseApiClient[ExampleStub]):
73+
class MyApiClient(BaseApiClient[ExampleAsyncStub]):
6974
def __init__(self, server_url: str, *, connect: bool = True):
7075
super().__init__(
71-
server_url, ExampleStub, connect=connect
76+
server_url,
77+
# We need to type ignore here because the generated normal and
78+
# async stubs are not type-compatible with each other.
79+
ExampleStub, # type: ignore[arg-type]
80+
connect=connect
7281
)
7382
self._broadcaster = GrpcStreamBroadcaster(
7483
"stream",

0 commit comments

Comments
 (0)