FlatBuffers
An open source project by FPL.
 All Classes Namespaces Files Functions Variables Properties Groups Pages
Use in Python

Before you get started

Before diving into the FlatBuffers usage in Python, it should be noted that the Tutorial page has a complete guide to general FlatBuffers usage in all of the supported languages (including Python). This page is designed to cover the nuances of FlatBuffers usage, specific to Python.

You should also have read the Building documentation to build flatc and should be familiar with Using the schema compiler and Writing a schema.

FlatBuffers Python library code location

The code for the FlatBuffers Python library can be found at flatbuffers/python/flatbuffers. You can browse the library code on the FlatBuffers GitHub page.

Testing the FlatBuffers Python library

The code to test the Python library can be found at flatbuffers/tests. The test code itself is located in py_test.py.

To run the tests, use the PythonTest.sh shell script.

Note: This script requires python to be installed.

Using the FlatBuffers Python library

Note: See Tutorial for a more in-depth example of how to use FlatBuffers in Python.

There is support for both reading and writing FlatBuffers in Python.

To use FlatBuffers in your own code, first generate Python classes from your schema with the --python option to flatc. Then you can include both FlatBuffers and the generated code to read or write a FlatBuffer.

For example, here is how you would read a FlatBuffer binary file in Python: First, import the library and the generated code. Then read a FlatBuffer binary file into a bytearray, which you pass to the GetRootAsMonster function:

1 import MyGame.Example as example
2 import flatbuffers
3 
4 buf = open('monster.dat', 'rb').read()
5 buf = bytearray(buf)
6 monster = example.GetRootAsMonster(buf, 0)

Now you can access values like this:

1 hp = monster.Hp()
2 pos = monster.Pos()

Text Parsing

There currently is no support for parsing text (Schema's and JSON) directly from Python, though you could use the C++ parser through SWIG or ctypes. Please see the C++ documentation for more on text parsing.