Skip to content

[Python] Generated type annotations do not pass mypy strict #29528

Description

@alexprengere

Hi! Here is a request to improve pyi Python type annotations generated.
Using the latest protoc version, and assuming this proto file:

syntax = "proto3";

message X {
  string s = 1;
}

message M {
  repeated X xs = 1;
}

After generating the code and pyi file:

$ protoc repro.proto --python_out=. --pyi_out=.

Here is the generated pyi file:

from google.protobuf.internal import containers as _containers
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from collections.abc import Iterable as _Iterable, Mapping as _Mapping
from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union

DESCRIPTOR: _descriptor.FileDescriptor

class X(_message.Message):
    __slots__ = ("s",)
    S_FIELD_NUMBER: _ClassVar[int]
    s: str
    def __init__(self, s: _Optional[str] = ...) -> None: ...

class M(_message.Message):
    __slots__ = ("xs",)
    XS_FIELD_NUMBER: _ClassVar[int]
    xs: _containers.RepeatedCompositeFieldContainer[X]
    def __init__(self, xs: _Optional[_Iterable[_Union[X, _Mapping]]] = ...) -> None: ...

mypy (the standard Python type checker) raises a type-arg issue in strict mode:

# python -m mypy repro_pb2.pyi  --strict, needs types-protobuf
repro_pb2.pyi:19: error: Missing type arguments for generic type "Mapping"  [type-arg]

In this example, the _Mapping is indeed lacking type arguments, and could be typed as Mapping[str, str].
AFAICT this is the only issue I encountered of such type. Fixing it could help the adoption of static typing of projects relying on generated protobuf code.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestuntriagedauto added to all issues by default when created.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions