FlatBuffers
An open source project by FPL.
|
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.
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.
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.
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:
Now you can access values like this:
The Flatbuffers python library also has support for accessing scalar vectors as numpy arrays. This can be orders of magnitude faster than iterating over the vector one element at a time, and is particularly useful when unpacking large nested flatbuffers. The generated code for a scalar vector will have a method <vector name>AsNumpy()
. In the case of the Monster example, you could access the inventory vector like this:
instead of
Numpy is not a requirement. If numpy is not installed on your system, then attempting to access one of the *asNumpy()
methods will result in a NumpyRequiredForThisFeature
exception.
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.