Skip to content

treeo.Immutable

Mixin that makes a class immutable. It adds a .replace() and .mutable() methods to the class which let you modify the state by creating a new objects.

is_mutable: bool property readonly

Returns:

Type Description
bool

True if the object is mutable.

replace(self, **kwargs)

Returns a copy of the Tree with the given fields specified in kwargs updated to the new values.

Examples:

@dataclass
class MyTree(to.Tree, to.Immutable):
    x: int = to.node()

tree = MyTree(x=1)

# increment x by 1
tree = tree.replace(x=tree.x + 1)

Parameters:

Name Type Description Default
**kwargs

The fields to update.

{}

Returns:

Type Description
~A

A new Tree with the updated fields.

Source code in treeo/mixins.py
def replace(self: A, **kwargs) -> A:
    """
    Returns a copy of the Tree with the given fields specified in `kwargs`
    updated to the new values.

    Example:

    ```python
    @dataclass
    class MyTree(to.Tree, to.Immutable):
        x: int = to.node()

    tree = MyTree(x=1)

    # increment x by 1
    tree = tree.replace(x=tree.x + 1)
    ```

    Arguments:
        **kwargs: The fields to update.

    Returns:
        A new Tree with the updated fields.
    """
    tree: tree_m.Tree = tree_m.copy(self)

    with tree_m._make_mutable_toplevel(tree):
        for key, value in kwargs.items():
            if not hasattr(tree, key):
                raise TypeError(f"Field '{key}' does not exist.")

            setattr(tree, key, value)

    tree._update_local_metadata()
    # return a copy to potentially update metadata
    return tree