Python Guide

This document will introduce how to use bitproto with Python language.


The python file generated by bitproto file is in Python 3, uses the typing hint and dataclasses. So make sure you are using Python3.7+ to use bitproto in Python.

Compile bitproto for Python

Firstly, run the bitproto compiler to generate code for Python:

$ bitproto py pen.bitproto

Where the pen.bitproto is introduced in earlier section An example bitproto.

We will find that bitproto generates us a file named, which contains the mapped classes, constants and api methods etc.

In the generated

  • The enum Color in bitproto is mapped to an enum.IntEum class, and the enum values are mapped to constants as well:

    class Color(IntEnum): # 3 bit
       COLOR_UNKNOWN = 0
       COLOR_RED = 1
       COLOR_BLUE = 2
       COLOR_GREEN = 3
    COLOR_RED: Color = Color.COLOR_RED
    COLOR_BLUE: Color = Color.COLOR_BLUE
  • The Timestamp in bitproto is also mapped to a typing hint alias:

    Timestamp = int # 64bit
  • The message Pen in bitproto is mapped to a dataclass decorated class in Python:

    class Pen(bp.MessageBase):
        BYTES_LENGTH: ClassVar[int] = 9
        color: Color = 0 # 3bit
        produced_at: Timestamp = field(default_factory=bp_default_factory_Timestamp) # 64bit
  • The compiler also generates two method on the class Pen, the encoder and the decoder:

    def encode(self) -> bytearray:
    def decode(self, s: bytearray) -> None:

Install bitproto Python library

Bitproto serialization requires a language-specific library to work, the generated encoder and decoder depends on the bitproto Python library underlying.

Install the bitproto Python library via pip:

$ pip install bitprotolib

The source code of the bitproto Python library is hosted on Github.

Run the code

Now, we create a file named and put the following code in it:

import pen_bp as bp

# Encode
p = bp.Pen(color=bp.COLOR_RED, produced_at=1611515729966)
s = p.encode()

# Decode
p1 = bp.Pen()

# Print in json format

In the code above, we firstly create a p instance of type Pen with data initilization, then call a method p.encode() to encode p and return the encoded buffer s, which is an bytearray.

In the decoding part, we construct another p1 instance of type Pen with zero initilization, then call a method p1.decode() to decode bytes from buffer s into p1.

The compiler also generates a method to_json() to return the json string format of the structure.

Let’s run it:

$ python
{"color": 1, "produced_at": 1611515729966}