skbio.tree.TreeNode.copy#
- TreeNode.copy(deep=False)[source]#
Return a copy of self using an iterative approach.
- Parameters:
- deepbool, optional
Whether to perform a deep (True) or shallow (False, default) copy of node attributes.
Added in version 0.6.2.
Changed in version 0.7.0: The default value has been changed to False.
- Returns:
- TreeNode
A new copy of self.
Changed in version 0.6.3: Node attribute caches will not be copied.
Changed in version 0.7.4: Can redirect node references to the copied tree.
See also
Notes
This method iteratively copies the current node and its descendants. That is, if the current node is not the root of the tree, only the subtree below the node, instead of the entire tree, will be copied.
All nodes and their attributes except for caches will be copied. The copies are new objects rather than references to the original objects. The distinction between deep and shallow copies only applies to each node attribute.
If node attributes are references to other nodes in the tree, they will be redirected to the new nodes in the copied tree, rather than the old nodes in the original tree. However, node references nested inside compound attributes will not be redirected in the shallow copy mode (they will when deep=True is added to the function call).
Examples
>>> from skbio import TreeNode >>> tree = TreeNode.read(["(a,b)c;"]) >>> a, b = tree.find("a"), tree.find("b")
The function’s behavior will be demonstrated using these node attributes:
>>> a.length = 1.0 # built-in attribute >>> a.label = "marker" # custom simple attribute >>> a.values = [[1, 2]] # custom compound attribute >>> a.partner = b # direct node reference >>> a.links = [b] # nested node reference
By default, the function makes a shallow copy of the tree, in which only the outer-most level of each node attribute is copied, whereas nested attributes are shared as references.
>>> shallow = tree.copy() >>> shallow_a = shallow.find("a") >>> shallow_a is a False >>> shallow_a.length 1.0 >>> shallow_a.label 'marker' >>> shallow_a.values [[1, 2]] >>> shallow_a.values is a.values False >>> shallow_a.values[0] is a.values[0] True
Attributes that are references to other nodes in the tree are redirected to the corresponding nodes in the copied tree. However, node references nested inside compound attributes still point to the original tree.
>>> shallow_a.partner is shallow.find("b") True >>> shallow_a.links[0] is b True
A deep copy also copies nested values and redirects nested node references:
>>> deep = tree.copy(deep=True) >>> deep_a, deep_b = deep.find("a"), deep.find("b") >>> deep_a.values is a.values False >>> deep_a.values[0] is a.values[0] False >>> deep_a.partner is deep_b True >>> deep_a.links[0] is deep_b True