{"id":1262,"library":"optree","title":"Optimized PyTree Utilities","description":"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.","status":"active","version":"0.19.0","language":"python","source_language":"en","source_url":"https://github.com/metaopt/optree","tags":["pytree","tree-traversal","functional-programming","python>=3.9","data-structures"],"install":[{"cmd":"pip install optree","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Required for type hinting support, especially for Python versions older than 3.12.","package":"typing-extensions","optional":false}],"imports":[{"symbol":"tree_flatten","correct":"from optree import tree_flatten"},{"symbol":"tree_unflatten","correct":"from optree import tree_unflatten"},{"symbol":"tree_map","correct":"from optree import tree_map"},{"symbol":"register_pytree_node","correct":"from optree import register_pytree_node"},{"note":"While `from optree import pytree` works, using `import optree.pytree as pt` is a common alias for convenience, especially since v0.14.1 for its `tree_*` aliases.","wrong":"from optree import pytree","symbol":"pytree","correct":"import optree.pytree as pt"}],"quickstart":{"code":"from optree import tree_map\n\ndef add_one(x):\n    return x + 1\n\ntree = {'a': 1, 'b': [2, 3], 'c': {'d': 4}}\nmapped_tree = tree_map(add_one, tree)\nprint(mapped_tree)\n\nfrom optree import tree_flatten, tree_unflatten, PyTreeSpec\n\nleaves, treespec = tree_flatten(tree)\nprint(f\"Leaves: {leaves}\")\nprint(f\"TreeSpec: {treespec}\")\n\nreconstructed_tree = tree_unflatten(treespec, [l * 10 for l in leaves])\nprint(f\"Reconstructed tree with modified leaves: {reconstructed_tree}\")","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade Python to 3.8+ (preferably 3.9+) or pin optree to `<0.14.0`.","message":"Python 3.7 support was dropped in optree v0.14.0. Users on Python 3.7 must upgrade their Python version or use optree versions prior to 0.14.0.","severity":"breaking","affected_versions":">=0.14.0"},{"fix":"Update code to use the current API. Refer to optree documentation for alternatives to key path APIs and `functools.partial` for `optree.Partial`.","message":"Deprecated key path APIs and `optree.Partial` were removed in optree v0.15.0. Any code relying on these older APIs will break.","severity":"breaking","affected_versions":">=0.15.0"},{"fix":"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')`.","message":"When registering a custom PyTree node type using `optree.register_pytree_node` or `optree.register_pytree_node_class`, a `namespace` argument is explicitly required. This prevents accidental collisions between different libraries registering the same type with different behaviors in the same Python interpreter.","severity":"gotcha","affected_versions":"All versions"},{"fix":"If `None` should be processed as a leaf, use `none_is_leaf=True` in relevant functions: `tree_map(func, tree, none_is_leaf=True)`.","message":"By default, `None` is treated as a non-leaf node with zero children. This means it's part of the tree structure (`treespec`), not the list of leaves. To treat `None` as a leaf node, you must explicitly pass `none_is_leaf=True` to functions like `tree_flatten` or `tree_map`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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`.","message":"Custom `flatten_func` implementations for `register_pytree_node` must include a proper termination condition to prevent infinite recursion, especially if the children can be of the same type as the current node. This can lead to a `RecursionError`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Update import statements. For example, change `from optree import accessor` to `from optree import accessors`.","message":"Module naming conventions changed in v0.16.0, affecting direct imports. Specifically, `optree.accessor` became `optree.accessors`, `optree.integration` became `optree.integrations`, etc.","severity":"breaking","affected_versions":">=0.16.0"},{"fix":"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`.","message":"Building `optree` from source requires C++ build tools (like `g++` or `clang++`) and `cmake` in the environment. This issue commonly arises when installing on minimal distributions (e.g., Alpine Linux) or when pre-built wheels are not available for the specific Python version/platform, forcing a source build.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'0.19.0':37 '3.9':57 'activ':43 'arbitrarili':16 'contain':19 'current':34 'cycl':45 'data':59 'data-structur':58 'develop':44 'effici':22 'flatten':25 'frequent':47 'function':29,54 'functional-program':53 'librari':9,40 'maintain':41 'map':28 'nest':17 'optim':1,7 'optre':4 'program':55 'provid':21 'python':8,18,56 'pytre':2,13,49 'releas':48 'structur':32,60 'travers':52 'tree':31,51 'tree-travers':50 'unflatten':26 'util':3,23 'version':35 'work':11","created_at":"2026-04-06T16:56:59.395932+00:00","updated_at":"2026-04-16T17:47:47.028533+00:00","problems":[{"fix":"Upgrade `typing_extensions` to a recent version: `pip install --upgrade typing-extensions`","cause":"This error typically occurs when the `typing_extensions` package installed in your environment is an outdated version that does not provide the `NamedTuple` type, which `optree` or its dependencies (like Keras) require.","error":"ImportError: cannot import name 'NamedTuple' from 'typing_extensions'"},{"fix":"Install `optree` using pip: `pip install optree`","cause":"The `optree` library is not installed in your current Python environment.","error":"ModuleNotFoundError: No module named 'optree'"},{"fix":"Upgrade `optree` to the latest version: `pip install --upgrade optree`","cause":"This error indicates that the installed `optree` version is too old and lacks features like `dict_insertion_ordered`, which newer versions of dependent libraries (e.g., PyTorch) might expect.","error":"AttributeError: module 'optree' has no attribute 'dict_insertion_ordered'"},{"fix":"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.","cause":"This usually happens when a custom PyTree node's `__tree_flatten__` (or `tree_flatten`) method, or the `is_leaf` predicate, is implemented in a way that leads to infinite recursion during tree traversal, without a proper termination condition for subtrees.","error":"RecursionError: Maximum recursion depth exceeded during flattening the tree."},{"fix":"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.","cause":"This error often occurs when `optree` (which sorts dictionary keys by default for deterministic flattening) encounters a dictionary with heterogeneous keys (e.g., a mix of integers and strings) that cannot be directly compared.","error":"TypeError: '<' not supported between instances of 'int' and 'str'"}],"ecosystem":"pypi","meta_description":null,"install_score":50,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.20.0","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/metaopt/optree","docs":"https://optree.readthedocs.io","changelog":null,"pypi":"https://pypi.org/project/optree/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["data","serialization","ai-ml"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":"draft"}}