BTrees
BTrees is a Python package that provides a set of scalable, persistent object containers built around a modified BTree data structure. It is heavily optimized for use within ZODB's "optimistic concurrency" paradigm, offering efficient storage and retrieval of large mappings by only loading relevant nodes into memory. The current version is 6.3, released on November 16, 2025, with an active release cadence, often aligning with Python version support.
Warnings
- breaking BTrees regularly drops support for older Python versions with new major/minor releases. Version 6.3 requires Python >=3.10. Older versions like 3.7, 3.8, and 3.9 are no longer supported by recent BTrees releases (e.g., 6.0 and 6.2).
- gotcha When using custom objects as keys in BTrees (especially OOBTree) that are intended for persistence, ensure these objects implement proper comparison methods (`__lt__`, `__le__`, `__eq__`, `__hash__`). Python's default object comparison (by memory address) leads to non-deterministic order and problematic behavior upon deserialization if not handled correctly.
- gotcha The BTrees library provides different modules for specific key/value types (e.g., `IIBTree` for integer keys/values, `OOBTree` for arbitrary objects). Mixing key/value types that do not match the chosen BTree variant (e.g., putting strings into an `IIBTree`) can lead to `TypeError` or other unexpected runtime issues.
- gotcha Unlike standard Python `dict.setdefault()`, the `BTrees.BTree.setdefault()` method requires a default value argument. It does not implicitly default to `None`.
- gotcha In versions prior to 4.9.2, set-like operations (`union`, `intersection`, `difference`, `multiunion`) could produce incorrect results if input iterables were not pre-sorted. While newer versions automatically sort internally, for large datasets, providing pre-sorted iterables can still offer performance benefits.
Install
-
pip install BTrees
Imports
- OOBTree
from BTrees.OOBTree import OOBTree
- IIBTree
from BTrees.IIBTree import IIBTree
- IOBTree
from BTrees.IOBTree import IOBTree
- OIBTree
from BTrees.OIBTree import OIBTree
Quickstart
from BTrees.OOBTree import OOBTree
# Create an in-memory Object-Object BTree
my_btree = OOBTree()
# Insert key-value pairs (like a dictionary)
my_btree['apple'] = 1
my_btree['banana'] = 2
my_btree['cherry'] = 3
my_btree['date'] = 4
print(f"BTree after insertions: {list(my_btree.items())}")
# Access values by key
print(f"Value for 'banana': {my_btree['banana']}")
# Iterate over sorted keys
print("Keys in sorted order:")
for key in my_btree.keys():
print(key)
# Check for key existence
print(f"'apple' in btree: {'apple' in my_btree}")
print(f"'grape' in btree: {'grape' in my_btree}")
# Delete a key
del my_btree['cherry']
print(f"BTree after deleting 'cherry': {list(my_btree.items())}")
# Example of getting a value with a default
value_or_default = my_btree.get('fig', 'default_value')
print(f"Value for 'fig' (with default): {value_or_default}")