To use protoletariat to fix imports in generated Python code, you must implement a subclass of FileDescriptorSetGenerator. This base class provides the fix_imports method, which automates the process of rewriting AST imports in files generated by protoc or buf to ensure they work correctly in a Python environment.
To use fix_imports, you must provide:
python_out: The directory where the generated Python files reside.create_package: A boolean indicating whether to create __init__.py files to form Python packages.overwrite_callback: A function Callable[[Path, str], None] that takes the file Path and the new_code (string) and performs the actual write operation.module_suffixes: A sequence of suffixes to look for (e.g., ['.py', '.pyi']).exclude_imports_glob: A sequence of glob patterns to ignore specific imports (e.g., ['google/protobuf/*']).
class MyGenerator(FileDescriptorSetGenerator):
def generate_file_descriptor_set_bytes(self) -> bytes:
# Return bytes of a FileDescriptorSet
...
# Usage
generator = MyGenerator()
generator.fix_imports(
python_out=Path("out/"),
create_package=True,
overwrite_callback=lambda path, code: path.write_text(code),
module_suffixes=".py",
exclude_imports_glob=["google/protobuf/*"]
)