Skip to content

Python .pyi stubs not defining optional boolean fields correctly. #20372

Open
@cobusc

Description

What version of protobuf and what language are you using?
Version: protobuf==5.29.3
Language: Python

What operating system (Linux, Windows, ...) and version?
Linux 6.11.0-14-generic #15-Ubuntu SMP PREEMPT_DYNAMIC x86_64 GNU/Linux

What runtime / compiler are you using (e.g., python version or gcc version)
Multiple Python versions

What did you do?
I compiled .proto files, and the generated .pyi stubs was not correct. Examples:

Example 1 (syntax proto2):

syntax = "proto2";

message Test2 {
  optional uint32 an_integer = 1;
  optional bool a_boolean = 2;
}

generated the following .pyi file:

from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional

DESCRIPTOR: _descriptor.FileDescriptor

class Test2(_message.Message):
    __slots__ = ("an_integer", "a_boolean")
    AN_INTEGER_FIELD_NUMBER: _ClassVar[int]
    A_BOOLEAN_FIELD_NUMBER: _ClassVar[int]
    an_integer: int
    a_boolean: bool
    def __init__(self, an_integer: _Optional[int] = ..., a_boolean: bool = ...) -> None: ...

Note that a_boolean does not have the _Optional[] definition in __init__().

Example 2 (syntax proto3):

syntax = "proto3";

message Test3 {
  optional uint32 an_integer = 1;
  optional bool a_boolean = 2;
}

generated the following .pyi file:

from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional

DESCRIPTOR: _descriptor.FileDescriptor

class Test3(_message.Message):
    __slots__ = ("an_integer", "a_boolean")
    AN_INTEGER_FIELD_NUMBER: _ClassVar[int]
    A_BOOLEAN_FIELD_NUMBER: _ClassVar[int]
    an_integer: int
    a_boolean: bool
    def __init__(self, an_integer: _Optional[int] = ..., a_boolean: bool = ...) -> None: ...

Note that a_boolean does not have the _Optional[] definition in __init__().

What did you expect to see
In both cases above I expected the _Optional[] annotation for a_boolean.

What did you see instead?
Type annotation issues, like these, when checking my code:

Argument "a_boolean" to "Test2" has incompatible type "Optional[bool]"; expected "bool"  [arg-type]

It looks like the _Optional[] definition is explicitly not done for booleans, and this does not seem right.
Here is where it is excluded:
opening
closing

Someone else reported it to the grpc project, but it never made its way here:
grpc/grpc#33181

Activity

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

Metadata

Assignees

No one assigned

    Labels

    untriagedauto 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