Mypy-protobuf使用的Stubgen和通用的错误
当我使用 protoc-gen-mypy 插件时 使用 Protoc
为我的GRPC招待服务生成Mypy Stubs,我会遇到有关仿制药的错误。
这是我用来生成 forter_pb2_grpc.pyi
文件的命令:
python -m grpc_tools.protoc --plugin=protoc-gen-mypy=`which protoc-gen-mypy` -Iprotos --mypy_grpc_out=grpc protos/greeter.proto
这是 enterer_pb2_grpc.pyi
:
"""
@generated by mypy-protobuf. Do not edit manually!
isort:skip_file
"""
import abc
import greeter_pb2
import grpc
class GreeterStub:
"""The greeting service definition."""
def __init__(self, channel: grpc.Channel) -> None: ...
SayHello: grpc.UnaryUnaryMultiCallable[
greeter_pb2.HelloRequest,
greeter_pb2.HelloReply]
"""Sends a greeting"""
class GreeterServicer(metaclass=abc.ABCMeta):
"""The greeting service definition."""
@abc.abstractmethod
def SayHello(self,
request: greeter_pb2.HelloRequest,
context: grpc.ServicerContext,
) -> greeter_pb2.HelloReply:
"""Sends a greeting"""
pass
def add_GreeterServicer_to_server(servicer: GreeterServicer, server: grpc.Server) -> None: ...
当我运行 mypy
时,我在 forter_pb2_grpc.pyi
文件中获取此错误:
“一般性摩尔族可言”期望没有类型的参数,但给出了2个给定的
grpc
库中的实际定义是:
class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): ...
so, stubgen
生成这样的存根:
class UnaryUnaryMultiCallable(metaclass=abc.ABCMeta):
我不想编辑编辑什么 mypy-protobuf
生成,因为我通常编辑的是 stubgen
生成的内容。
我应该如何编辑 grpc/__ init __。pyi
stubgen
生成以制造 mypy
不抱怨的文件?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无需为
grpc
生成自己的存根-Stubs 已经做到了。该库将其用于类定义(请参阅在这里):
因此,只需执行
PIP install grpc-stubs
并删除grpc/**/*。pyi
grpc
stubs代码>应该解决问题。如果您不使用
grpc.aio
,以上是一个很好的解决方案。但是,如果您使用
grpc.aio
并具有从grpc.aio.ServerInterpector
类似的类中,例如:因为此
grpc-stubs
问题,您需要做一些手动的事情。我个人必须从头开始创建自己的存根(在
stubgen
的帮助下),因为我找不到与来自grpc-stubs
的存根合并的方法(例如声明合并 在打字条中起作用)。不要卸载
grpc-stubs
,因为您仍然需要它具有grpc_health
和grpc_reflection
的类型。我不包括我在此stackoverflow答案中所做的工作,因为它仅具有
grpc
和grpc.aio
的部分覆盖范围,并且取决于我的服务器代码。You don't need to generate your own stubs for
grpc
becausegrpc-stubs
already does that.And this library uses this for the class definition (see here):
So, just doing
pip install grpc-stubs
and removing yourgrpc/**/*.pyi
stubs forgrpc
should do the trick.The above is a good solution if you are not using
grpc.aio
.However, if you use
grpc.aio
and have, for instance, a class inheriting from agrpc.aio.ServerInterceptor
like this:Because of this
grpc-stubs
issue, you'll need to do something more manual.I personally had to create my own stubs from scratch (with the help of
stubgen
) because I couldn't find a way to merge custom stubs with stubs coming fromgrpc-stubs
(like how Declaration Merging would work in TypeScript).Don't uninstall
grpc-stubs
because you'll still need it to have types forgrpc_health
andgrpc_reflection
.I'm not including what I did in this StackOverflow answer because it is only has a partial coverage of
grpc
andgrpc.aio
and it depends on my server code.