Proto Schema Parser
A pure Python library for parsing Protobuf `.proto` files into an Abstract Syntax Tree (AST)-like structure. It provides an intuitive object model for navigating and extracting information from parsed schema definitions. As of version 2.1.0, it primarily supports `proto3` syntax and offers a robust, actively maintained solution for programmatic schema inspection.
Common errors
-
AttributeError: 'ProtoFile' object has no attribute 'package_name'
cause Attempting to access an attribute on a parsed AST node (e.g., `ProtoFile`, `Message`) that no longer exists or has been renamed following the v2.0.0 AST refactor.fixThis often indicates an old access pattern. For example, if you used `parsed_proto.package_name` or `parsed_proto.package.name` in `1.x`, in `2.x` you should likely use `parsed_proto.package` directly to get the package string. Refer to the current documentation or inspect the `ProtoNode` objects for the correct attribute names. -
proto_schema_parser.exceptions.ParseError: Expected one of [IDENTIFIER, INT_LIT, STRING_LIT, ...]
cause The input `.proto` content contains a syntax error or an unsupported language construct, preventing the parser from building a valid Abstract Syntax Tree.fixCarefully review the `.proto` file for any grammatical mistakes, missing semicolons, incorrect keyword usage, or unclosed blocks. Ensure the file adheres to the Protobuf `proto3` specification (or `proto2` if you are aware of its parsing limitations with this library) at the specified line and column number in the error message.
Warnings
- breaking Version 2.0.0 introduced significant breaking changes due to a complete refactor of the internal Abstract Syntax Tree (AST) representation. Code written for 1.x versions that traverses the parsed object structure will likely fail when upgrading.
- gotcha The parser is primarily designed and tested for `proto3` syntax. While it may parse some `proto2` files, full `proto2` compatibility is not guaranteed, and some `proto2`-specific features (e.g., `optional`, `required` keywords, extensions) might not be fully represented or correctly parsed.
Install
-
pip install proto-schema-parser
Imports
- ProtoParser
from proto_schema_parser import ProtoParser
Quickstart
from proto_schema_parser import ProtoParser
proto_content = """
syntax = "proto3";
package my.package;
message MyMessage {
string name = 1;
int32 age = 2;
}
"""
parser = ProtoParser()
parsed_proto = parser.parse(proto_content)
print(f"Syntax: {parsed_proto.syntax}") # Output: Syntax: proto3
print(f"Package: {parsed_proto.package}") # Output: Package: my.package
print(f"Message Name: {parsed_proto.messages[0].name}") # Output: Message Name: MyMessage