Other configurations may work, but are not continuously tested currently.
We would be open to expanding this list - file an issue on the issue tracker.
Installation
The plugin can be installed with
pip3 install mypy-protobuf
To install unreleased
REV=main # or whichever unreleased git rev you'd like
pip3 install git+https://github.com/nipunn1313/mypy-protobuf.git@$REV
# For older (1.x) versions of mypy protobuf - you may need
pip3 install git+https://github.com/nipunn1313/mypy-protobuf.git@$REV#subdirectory=python
In order to run mypy on the generated code, you'll need to install
pip3 install mypy>=0.910 types-protobuf>=0.1.14
Usage
On posix, protoc-gen-mypy is installed to python's executable bin. Assuming that's
on your $PATH, you can run
The implementation of the plugin is in mypy_protobuf/main.py, which installs to
an executable protoc-gen-mypy. On windows it installs to protoc-gen-mypy.exe
Differences between the protobuf compiler (--pyi_out) and mypy-protobuf
(As of 11/17/2025)
mypy-protobuf generates stubs for GRPC services and clients
mypy-protobuf generates correctly typed HasField methods depending on field presence, pyi_out does not type HasField arguments
mypy-protobuf generates correctly typed constructors dependinding on field presence.
mypy-protobuf generates correctly typed HasField, WhichOneof, and ClearField methods.
There are differences in how mypy-protobuf and pyi_out generate enums. See this issue for details
Type aliases exported for HasField, WhichOneof and ClearField arguments
Parses comments as docstrings
mypy-protobuf marks enums, enum values, messages, message fields, services, and methods with @warnings.deprecated if the deprecation option is set to true.
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from collections.abc import Mapping as _Mapping
from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union
DESCRIPTOR: _descriptor.FileDescriptor
class Editions2024SubMessage(_message.Message):
__slots__ = ()
THING_FIELD_NUMBER: _ClassVar[int]
thing: str
def __init__(self, thing: _Optional[str] = ...) -> None: ...
class Editions2024Test(_message.Message):
__slots__ = ()
LEGACY_FIELD_NUMBER: _ClassVar[int]
EXPLICIT_SINGULAR_FIELD_NUMBER: _ClassVar[int]
MESSAGE_FIELD_FIELD_NUMBER: _ClassVar[int]
IMPLICIT_SINGULAR_FIELD_NUMBER: _ClassVar[int]
DEFAULT_SINGULAR_FIELD_NUMBER: _ClassVar[int]
legacy: str
explicit_singular: str
message_field: Editions2024SubMessage
implicit_singular: str
default_singular: str
def __init__(self, legacy: _Optional[str] = ..., explicit_singular: _Optional[str] = ..., message_field: _Optional[_Union[Editions2024SubMessage, _Mapping]] = ..., implicit_singular: _Optional[str] = ..., default_singular: _Optional[str] = ...) -> None: ...
Bring comments from .proto files to docstrings in .pyi files
Comments in the .proto files on messages, fields, enums, enum variants, extensions, services, and methods
will appear as docstrings in .pyi files. Useful in IDEs for showing completions with comments.
Types enum int values more strongly
Enum int values produce stubs which wrap the int values in NewType
enum MyEnum {
HELLO = 0;
WORLD = 1;
}
Will yield an enum type wrapper whose methods type to MyEnum.ValueType (a NewType(int) rather than int.
This allows mypy to catch bugs where the wrong enum value is being used.
Calling code may be typed as follows.
In python >= 3.7
# May need [PEP 563](https://www.python.org/dev/peps/pep-0563/) to postpone evaluation of annotations
# from __future__ import annotations # Not needed with python>=3.11 or protobuf>=3.20.0
def f(x: MyEnum.ValueType):
print(x)
f(MyEnum.Value("HELLO"))
With protobuf <= 3.20.0, for usages of cast, the type of x must be quoted
After protobuf >= 3.20.0 - ValueType exists in the python code and quotes aren't needed
until upstream protobuf includes ValueType
cast('MyEnum.ValueType', x)
Similarly, for type aliases with protobuf < 3.20.0, you must either quote the type or hide it behind TYPE_CHECKING
from typing import Tuple, TYPE_CHECKING
HELLO = Tuple['MyEnum.ValueType', 'MyEnum.ValueType']
if TYPE_CHECKING:
HELLO = Tuple[MyEnum.ValueType, MyEnum.ValueType]
Enum int impl details
mypy-protobuf autogenerates an instance of the EnumTypeWrapper as follows.
If py_generic_services is set in your proto file, then mypy-protobuf will
generate service stubs. If you want GRPC stubs instead - use the GRPC instructions.
readable_stubs
If readable_stubs is set, mypy-protobuf will generate easier-to-read stubs. The downside
to this approach - is that it's possible to generate stubs which do not pass mypy - particularly
in the case of name collisions. mypy-protobuf defaults to generating stubs with fully qualified
imports and mangled global-level identifiers to defend against name collisions between global
identifiers and field names.
If you are using proto3, then primitives cannot be represented as NULL on the wire -
only as their zero value. By default mypy-protobuf types message constructors to have
non-nullable primitives (eg int instead of Optional[int]). python-protobuf itself will
internally convert None -> zero value. If you intentionally want to use this behavior,
set this flag! We recommend avoiding this, as it can lead to developer error - confusing
NULL and 0 as distinct on the wire.
However, it may be helpful when migrating existing proto2 code, where the distinction is meaningful
By default mypy-protobuf will pull the leading and trailing comments from the deprecation option definition,
and insert it into the deprecation warning. This option will instead use a standard deprecation warning instead of comments.
Note that generated code for grpc will work only together with code for python and locations should be the same.
If you need stubs for grpc internal code we suggest using this package https://pypi.org/project/types-grpcio/
Async GRPC usage
mypy-protobuf generates stubs that are compatible with both sync and async usage, with a few caveats.
In a simple use case, the stubs work as expected.
stub = dummy_Pb2_grpc.DummyServiceStub(grpc.aio.insecure_channel("localhost:1234"))
result = await stub.UnaryUnary(dummy_pb2.DummyRequest(value="cprg"))
typing.assert_type(result, dummy_pb2.DummyReply)
If you need to explicitly type something as an async stub (class attr, etc) then you must use deferred annotations, and the async stub, as it does not exist at runtime.
_ClearFieldArgType, _WhichOneofArgType_<oneof_name>, _WhichOneofReturnType_<oneof_name> and _HasFieldArgType aliases
Where applicable, type aliases are generated for the arguments to ClearField, WhichOneof and HasField. These can be used to create typed functions for field manipulation:
Note the deferred evaluation (string reference, or from __future__ import annotations. This bypasses the fact that the alias does not exist on the runtime class)
Targeting python2 support
mypy-protobuf's drops support for targeting python2 with version 3.0. If you still need python2 support -