Skip to content

protobuf.plugin

A protoc plugin framework for Python.

File

Bases: Protocol

A Python file that will have content generated based on the operations on this object.

path instance-attribute

path

The path of the file to generate, relative to the output directory.

print

print(*args)

Add a line to the file.

Parameters:

Name Type Description Default
*args object

Elements to print on the line. Each argument is converted to a string element:

  • str values are printed verbatim.
  • int/float/bool as literals.
  • bytes as a bytes literal.
  • Ident as an imported name.
  • ScalarType, DescMessage, DescEnum, or DescExtension as imported symbols.
  • list values are recursively flattened.
  • Other values are formatted with f"{arg}".
()

ident

ident(name, *, type_only=False)

Return an identifier scoped to this file's module.

Parameters:

Name Type Description Default
name str

The symbol name.

required
type_only bool

If true, the import is emitted only inside an if TYPE_CHECKING: block.

False

Returns:

Type Description
Ident

An Ident linked to this file's module.

scope

scope(*args)

Open an indented scope.

Prints args as the scope header and indents all subsequent print() calls inside the context manager by one level.

Parameters:

Name Type Description Default
*args object

Elements to print as the scope header line.

()

Examples:

with f.scope("class Foo:"):
    f.print("field: str")

# Output:
# class Foo:
#     field: str

type_checking

type_checking()

Open an if TYPE_CHECKING: scope.

Emits if TYPE_CHECKING: as a scope header and marks all identifiers printed inside the context manager as type-only imports.

Raises:

Type Description
RuntimeError

If already inside a type-checking context.

Examples:

with f.type_checking():
    f.print("x: ", f.ident("Foo"))

# Output:
# if TYPE_CHECKING:
#     x: Foo
#
# The import for Foo is emitted under TYPE_CHECKING.

preamble

preamble(desc)

Add a DO NOT EDIT preamble derived from desc.

Parameters:

Name Type Description Default
desc DescFile

The file descriptor whose proto name is used in the preamble.

required

doc

doc(*args)

Open a Python docstring.

Prints opening """ (with args on the same line if provided) and closing """ on exit. If args are provided and nothing is printed inside the context manager, the docstring collapses to a single line. While the context is open, print() escapes \ and """ in string elements so they cannot break the docstring. scope() works normally inside for indented sections.

Parameters:

Name Type Description Default
*args object

Optional elements to print on the opening line after the triple-quote.

()

Examples:

with f.doc("A single-line docstring."):
    pass

# Output:
# """A single-line docstring."""
with f.doc("A short description."):
    f.print()
    f.print("Longer description.")

# Output:
# """A short description.
#
# Longer description.
# """
with f.doc("Get a user by ID."):
    f.print()
    with f.scope("Args:"):
        f.print("user_id: The unique identifier.")
    f.print()
    with f.scope("Returns:"):
        f.print("The matching user.")

# Output:
# """Get a user by ID.
#
# Args:
#     user_id: The unique identifier.
#
# Returns:
#     The matching user.
# """

Ident dataclass

Ident(name, module, type_only=False, _desc=None)

A Python identifier with its owning module.

Attributes:

Name Type Description
name str

The symbol name.

module Module

The module this identifier is imported from.

type_only bool

If true, the import is only emitted inside an if TYPE_CHECKING: block.

for_desc classmethod

for_desc(
    desc, *, type_only=False, escape_module_with_hash=False
)

Derive an importable identifier from a descriptor.

For DescFile, the returned name is the module for the file within its Module, (e.g. baz_pb in .foo.bar). For message, enum, and extension descriptors the name is the generated symbol.

Parameters:

Name Type Description Default
desc DescEnum | DescMessage | DescExtension | DescFile

A file, message, enum, or extension descriptor.

required
type_only bool

If true, the import is only emitted inside an if TYPE_CHECKING: block.

False
escape_module_with_hash bool

If true, the module name is escaped with a hash suffix to avoid potential collisions with other artifacts.

False

Returns:

Type Description
Ident

An Ident linked to the derived module.

Module dataclass

Module(path)

A Python module path used for import resolution.

Attributes:

Name Type Description
path str

The import path of the module. If it starts with a ., it is treated as relative to the generation root; otherwise it is a fully qualified import.

for_desc classmethod

for_desc(desc, suffix, *, escape_with_hash=False)

Derive a relative module path from a file descriptor.

Intermediate path components are sanitized (Python keywords and the _pb suffix are escaped). The final component gets suffix appended.

Parameters:

Name Type Description Default
desc DescFile

The file descriptor.

required
suffix str

Appended to the final path component, e.g. "_pb" turns any.proto into module any_pb.

required
escape_with_hash bool

If true, the module name is escaped with a hash suffix to avoid potential collisions with other artifacts.

False

Returns:

Type Description
Module

A relative Module.

Examples:

google/protobuf/any.proto with suffix "_pb" produces .google.protobuf.any_pb.

ident

ident(name, *, type_only=False)

Return an identifier belonging to this module.

Parameters:

Name Type Description Default
name str

The symbol name.

required
type_only bool

If true, the import is only emitted inside an if TYPE_CHECKING: block.

False

Returns:

Type Description
Ident

A Ident linked to this module.

module

module(name)

Return a child module.

Parameters:

Name Type Description Default
name str

The child module name.

required

Returns:

Type Description
Module

A new Module with name appended to this module's path.

Schema

Bases: Protocol[T_co]

Schema describes the files and types that the plugin is requested to generate.

options property

options

Parsed plugin options.

files_to_generate property

files_to_generate

Files we are asked to generate.

all_files property

all_files

All files including transitive dependencies.

generate_file

generate_file(path: str) -> File
generate_file(desc: DescFile, suffix: str) -> File

Create a generated file.

Two calling conventions are supported:

generate_file(path) Create a file at an arbitrary output path relative to the generation root.

generate_file(desc, suffix) Create a file with a path derived from the descriptor: <proto path without .proto><suffix>.py.

Parameters:

Name Type Description Default
path_or_desc str | DescFile

Either a string path (e.g. "my_package/__init__.py") or a DescFile to derive the path from.

''
suffix str

When path_or_desc is a DescFile, the suffix to append, with file extension. For example, "_pb.py" turns google/protobuf/any.proto into google/protobuf/any_pb.py, while "_pb.txt" turns it into google/protobuf/any_pb.txt.

''

Returns:

Type Description
File

A new File for writing content into.

run

run(
    name: str,
    version: str,
    generate: Callable[[Schema[None]], None],
    /,
    *,
    minimum_edition: int = minimum_supported_edition,
    maximum_edition: int = maximum_supported_edition,
) -> None
run(
    name: str,
    version: str,
    options: type[D],
    generate: Callable[[Schema[D]], None],
    /,
    *,
    minimum_edition: int = minimum_supported_edition,
    maximum_edition: int = maximum_supported_edition,
) -> None
run(
    name: str,
    version: str,
    options: Callable[[str], T],
    generate: Callable[[Schema[T]], None],
    /,
    *,
    minimum_edition: int = minimum_supported_edition,
    maximum_edition: int = maximum_supported_edition,
) -> None

Run a protoc plugin.

This is the single entry point for any protoc plugin. It handles the full lifecycle: reading the request, parsing options, building descriptors, calling the generate callback, and writing the response.

Two calling conventions are supported:

run(name, version, generate)
run(name, version, options, generate)

Parameters:

Name Type Description Default
name str

Plugin name, used for --version output.

required
version str

Plugin version, used for --version output.

required
options_or_generate type[DataclassInstance] | Callable[..., Any]

If a dataclass type, parse key=value pairs into it. If a callable and generate is omitted, used directly as the generate callback. Otherwise, called with the raw parameter string.

required
generate Callable[[Schema[Any]], None] | None

Callback invoked with the schema.

None
minimum_edition int

Minimum edition supported by this plugin. Defaults to the runtime's minimum_supported_edition.

minimum_supported_edition
maximum_edition int

Maximum edition supported by this plugin. Defaults to the runtime's maximum_supported_edition.

maximum_supported_edition

get_comments

get_comments(desc)

Get comments on the element in the protobuf source.

get_package_comments

get_package_comments(desc)

Get comments on the package element in the protobuf source.

get_syntax_comments

get_syntax_comments(desc)

Get comments on the syntax element in the protobuf source.