Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
I have the following code:
from proto.example_pb2 import SomeMessage from google.protobuf.message import Message def request(...) -> Message: ... result: SomeMessage = request( ... )
Request will return a protobuf message which can vary depending on the input parameters. This is giving the following mypy error:
Now, I understand why this is happening:
The reasoning behind this code is that while
The only solution I thought about is to use
Can anyone help me figure this out?
There exists a cast method in the typing module which might allow you to force a conversion like this.
Generally speaking, a single method that could return a variety of types based on the input - is not a strongly typed method - so you will have to cast. The input string is “stringly typed” encoding the type in a way that bypasses the type system.
One pattern might be to have N typed methods (either with overload like you mention - or even N methods with different names that don’t require arguments).
If you know which message each kind of request returns, this sounds very much like RPC services. In such case, I would expect your RPC service (defined in Protobuf) to result in a generated Python typestub to the effect of: