Python Guide

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

Prerequisites

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 pen_bp.py, which contains the mapped classes, constants and api methods etc.

In the generated pen_bp.py:

  • The enum Color in bitproto is mapped to a typing hint alias, and the enum values are mapped to constants:

    Color = int # 3bit
    COLOR_UNKNOWN: Color = 0
    COLOR_RED: Color = 1
    COLOR_BLUE: Color = 2
    COLOR_GREEN: Color = 3
    
  • 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:

    @dataclass
    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:
        pass
    
    def decode(self, s: bytearray) -> None:
        pass
    

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 main.py 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()
p1.decode(s)

# Print in json format
print(p1.to_json())

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 main.py
{"color": 1, "produced_at": 1611515729966}