OpTree is an optimized Python library for working with PyTrees, which are arbitrarily nested Python containers. It provides efficient utilities for flattening, unflattening, and mapping functions over tree structures. The current version is 0.19.0, and the library maintains an active development cycle with frequent releases.
pip install optreeVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates the core `tree_map` function to apply a transformation to all leaves of a PyTree, and also shows how to flatten a PyTree into leaves and a structure (`treespec`) and then unflatten it back, potentially with modified leaves.
Upgrade Python to 3.8+ (preferably 3.9+) or pin optree to `<0.14.0`.
Update code to use the current API. Refer to optree documentation for alternatives to key path APIs and `functools.partial` for `optree.Partial`.
Always provide a unique, non-empty `namespace` string (e.g., 'mylibrary.pytrees') when registering custom PyTree nodes. Example: `optree.register_pytree_node(MyClass, flatten_func, unflatten_func, namespace='my.namespace')`.
If `None` should be processed as a leaf, use `none_is_leaf=True` in relevant functions: `tree_map(func, tree, none_is_leaf=True)`.
Carefully design `flatten_func` to ensure that it eventually produces only leaf nodes or built-in non-leaf types, or explicitly handle recursion depth. The library defines `MAX_RECURSION_DEPTH`.
Update import statements. For example, change `from optree import accessor` to `from optree import accessors`.
Ensure that C++ build tools and `cmake` are installed in the environment where `optree` is being built. For example, on Alpine Linux, this typically involves `apk add build-base g++ cmake`. On Debian/Ubuntu, use `apt-get install build-essential g++ cmake`.
Upgrade `typing_extensions` to a recent version: `pip install --upgrade typing-extensions`
Install `optree` using pip: `pip install optree`
Upgrade `optree` to the latest version: `pip install --upgrade optree`
Review the `__tree_flatten__` (or `tree_flatten`) implementation for custom PyTree nodes or the `is_leaf` function to ensure that children are correctly identified and that the recursion terminates for leaf nodes.
Ensure dictionary keys are of a comparable type or use `collections.OrderedDict` if insertion order is important and keys are heterogeneous. Alternatively, provide a custom `is_leaf` function if specific keys should be treated as leaves without sorting.