optree v0.9.0
What's New
Now optree
preserves dict
/ defaultdict
key order in the output of tree_unflatten
, tree_map
, and tree_map_with_path
.
This behavior needs extra operations during flattening/unflattening. There would be performance regression for dict
and defaultdict
. No impact is added for other collection types, such as OrderedDict
, list
, tuple
.
optree v0.8.0: the output dict
from tree_unflatten
is stored in sorted order.
tree_flatten
and tree_unflatten
will lose the information above the insertion order of the input dict
. Map over a dict
with the identity function will change the key order.
>>> optree.tree_map(lambda x: x, {'b': 2, 'a': 1})
{'a': 1, 'b': 2}
optree v0.9.0: the output dict
from tree_unflatten
will have the consistent key order with the input dict
.
>>> optree.tree_map(lambda x: x, {'b': 2, 'a': 1})
{'b': 2, 'a': 1}
As the key order is preserved, it's safe to use tree_map
to process "unordered dict" (builtins.dict
) (e.g., **kwargs
in functions). In this case, users no longer need to convert dict
to OrderedDict
manually.
def func(*args, **kwargs):
args, kwargs = optree.tree_map(do_something, (args, kwargs))
# optree v0.8.0: args, kwargs = optree.tree_map(do_something, (args, OrderedDict(kwargs)))
...
Note that tree_map
still maps the leaves in sorted key order (the same order as tree_flatten
and tree_leaves
).
>>> leaves = []
...
... def add_leaves(x):
... leaves.append(x)
... return x
...
>>> ptree.tree_map(add_leaves, {'b': 2, 'a': 1})
{'b': 2, 'a': 1}
>>> leaves
[1, 2]
Breaking Changes
Revert "Change keyword argument initial
to initializer
for tree_reduce
to align with functools.reduce
". The previous change is reverted due to a documentation issue for Python (see also python/cpython#102757 and python/cpython#102759). The argument name is changed back to initial
in tree_reduce
. Users are recommended to use positional arguments.
Full Changelog [0.9.0] - 2023-03-23
Added
- Preserve dict key order in the output of
tree_unflatten
,tree_map
, andtree_map_with_path
by @XuehaiPan in #46.
Changed
- Change keyword argument
initializer
back toinitial
fortree_reduce
to align withfunctools.reduce
C implementation by @XuehaiPan in #47.
Full Changelog: v0.8.0...v0.9.0