Skip to content

Add metaclass=GeneratedProtocolMessageType to protobuf message class #581

@summylight

Description

@summylight

I'm working on our codebase to apply mypy-protobuf to generate pyi code. However, we have codes like:

from google.protobuf import json_format
from google.protobuf.reflection import GeneratedProtocolMessageType

def convert_model_to_pb(
        config: Config,
        pb_class: GeneratedProtocolMessageType,
        ignore_unknown_fields: bool = False) -> Message:
    return json_format.ParseDict(
        config.to_json(use_str_for_datetime=True),
        pb_class()
    )

This func accepts protobuf message class as parameters, and parse proto into json. We add GeneratedProtocolMessageType as its type. and mypy would report this error since GeneratedProtocolMessageType does not exist in generated pyi files:

error: Argument 2 to "convert_model_to_pb" has incompatible type "Type[Config]"; expected "GeneratedProtocolMessageType"  [arg-type]

I add metaclass=metaclass=GeneratedProtocolMessageType to pyi files and pass mypy check:

Class Config(_message.Message, metaclass=GeneratedProtocolMessageType)

Can mypy-protobuf support this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions