https://github.com/jkmnt/protobuf-typeddict
Create TypedDict definitions for protobuf json
https://github.com/jkmnt/protobuf-typeddict
protobuf protobuf-python typeddict typehints
Last synced: about 1 year ago
JSON representation
Create TypedDict definitions for protobuf json
- Host: GitHub
- URL: https://github.com/jkmnt/protobuf-typeddict
- Owner: jkmnt
- License: mit
- Created: 2024-10-07T17:13:22.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-03-13T22:28:53.000Z (over 1 year ago)
- Last Synced: 2025-06-14T03:05:42.463Z (about 1 year ago)
- Topics: protobuf, protobuf-python, typeddict, typehints
- Language: Python
- Homepage:
- Size: 7.81 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# protobuf-typeddict
Tiny tool for generating the TypedDicts describing the protobuf's `MessageToDict`/`ParseDict` (aka `json`) representations.
Some data are better manipulated as simple (typesafe) dicts instead of the python-protobuf's rich objects. Now the protobufs are just the binary serialization library.
## Example
Given this ...
```protobuf
message Project {
optional fixed64 id = 1;
optional float billing = 2;
optional bool is_active = 3;
}
message User {
optional int32 id = 1;
optional string name = 2;
repeated string email = 3;
map project = 4;
}
```
generates this:
```python
Project = TypedDict(
"Project",
{
"id": NotRequired[int],
"billing": NotRequired[float],
"is_active": NotRequired[bool],
}
)
User = TypedDict(
"User",
{
"id": NotRequired[int],
"name": NotRequired[str],
"email": list[str],
"project": dict[str, "Project"],
}
)
```
## Installation
```shell
pip install git+https://github.com/jkmnt/protobuf-typeddict.git
```
## Usage
### Cli
pb2td installs the script `pb2td`. Run it as
```shell
pb2td src_pb2.py dst.py
```
to generate the `dst.py` types.
### Programmatic
```python
import my_module_pb2
import pb2td
# the result is str
result = pb2tf.generate(my_module_pb2)
print(result)
```
NOTE: The pb2td makes TypedDicts from protoc-generated `_pb2.py`/`_pb3.py` files, not the `.proto`.
## Limitations
- No RPC/services. Just the plain data protobufs
- No well-known types (`datetime` etc)
- Enums are typed as int
- No pb2 extensions