borsh-construct
raw JSON → 0.1.0 verified Fri May 01 auth: no python
Python implementation of Borsh serialization, built on the Construct library. Version 0.1.0. Low release cadence.
pip install borsh-construct Common errors
error ModuleNotFoundError: No module named 'borsh' ↓
cause Installed borsh-construct but tried to import 'borsh' (the JavaScript-like package).
fix
Use 'from borsh_construct import ...' instead.
error AttributeError: module 'borsh_construct' has no attribute 'BorshStruct' ↓
cause Outdated version or misspelling (e.g., 'BorshStruct' vs 'BorshStruct<wrong>').
fix
Ensure you have the latest version: pip install --upgrade borsh-construct. Check spelling: it is 'BorshStruct'.
error construct.core.ConstructError: Error in field '...' : expected Sequence, got dict ↓
cause Passed a dict to a field that expects a list (e.g., Vec).
fix
Ensure that arrays are passed as lists, not dicts. For Vec fields, provide a list.
Warnings
gotcha borsh-construct uses the Construct library under the hood. If you mix borsh_construct types with pure construct types, serialization may fail silently or produce non-Borsh-compatible output. ↓
fix Always use types imported from borsh_construct rather than construct directly when working with Borsh serialization.
gotcha Borsh is strict about field order. When subclassing BorshStruct, field order in class definition matters and must match the schema exactly. ↓
fix Define fields in the same order as the schema you are conforming to. Do not assume alphabetical or insertion order.
Imports
- BorshStruct wrong
from borsh import BorshStructcorrectfrom borsh_construct import BorshStruct - U8, U16, U32, U64, U128, I8, I16, I32, I64, I128, F32, F64, String, Vec, Option, Enum, Struct
from borsh_construct import U8, U16, ...
Quickstart
from borsh_construct import BorshStruct, U8, U32, String, Vec
# Define a simple Borsh schema
class Person(BorshStruct):
name = String
age = U32
hobbies = Vec(String)
# Encode an instance
data = Person.encode({'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'coding']})
print('Encoded:', data.hex())
# Decode back
decoded = Person.decode(data)
print('Decoded:', decoded)