skbio.tree.TreeNode.cache_attr#
- TreeNode.cache_attr(func, cache_attrname, cache_type=<class 'list'>)[source]#
Cache attributes on internal nodes of the tree.
- Parameters:
- funcfunction
func will be provided the node currently being evaluated and must return a list of item (or items) to cache from that node or an empty list.
- cache_attrnamestr
Name of the attribute to decorate on containing the cached values
- cache_type{set, frozenset, list}
The type of the cache
- Raises:
- TypeError
If an cache_type that is not a set or a list is specified.
Notes
This method is particularly useful if you need to frequently look up attributes that would normally require a traversal of the tree.
WARNING: any cache created by this method will be invalidated if the topology of the tree changes (e.g., if TreeNode.invalidate_caches is called).
Examples
Cache the tip names of the tree on its internal nodes
>>> from skbio import TreeNode >>> tree = TreeNode.read(["((a,b,(c,d)e)f,(g,h)i)root;"]) >>> f = lambda n: [n.name] if n.is_tip() else [] >>> tree.cache_attr(f, 'tip_names') >>> for n in tree.traverse(include_self=True): ... print("Node name: %s, cache: %r" % (n.name, n.tip_names)) Node name: root, cache: ['a', 'b', 'c', 'd', 'g', 'h'] Node name: f, cache: ['a', 'b', 'c', 'd'] Node name: a, cache: ['a'] Node name: b, cache: ['b'] Node name: e, cache: ['c', 'd'] Node name: c, cache: ['c'] Node name: d, cache: ['d'] Node name: i, cache: ['g', 'h'] Node name: g, cache: ['g'] Node name: h, cache: ['h']