Use in Python {#flatbuffers_guide_use_python}

Before you get started

Before diving into the FlatBuffers usage in Python, it should be noted that the [Tutorial](@ref flatbuffers_guide_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](@ref flatbuffers_guide_building) documentation to build flatc and should be familiar with [Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and [Writing a schema](@ref flatbuffers_guide_writing_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]( python).

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 []( flatbuffers/blob/master/tests/

To run the tests, use the []( blob/master/tests/ shell script.

Note: This script requires python to be installed.

Using the FlatBuffers Python library

Note: See [Tutorial](@ref flatbuffers_guide_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:

    import MyGame.Example as example
    import flatbuffers

    buf = open('monster.dat', 'rb').read()
    buf = bytearray(buf)
    monster = example.GetRootAsMonster(buf, 0)

Now you can access values like this:

    hp = monster.Hp()
    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.