pythonsearchanytree

Findall() search functionality in python library 'anytree' returns NameError: 'findall' is not defined


I am using the anytree library in python for a project I am working on that utilizes the tree functionality of the library. I would like to be able to search within the tree, but the search commands shown in the documentation do not work.

This is an example tree directly from the documentation found here: https://anytree.readthedocs.io/en/latest/api/anytree.search.html#anytree.search.findall.

>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
|   |-- a
|   +-- d
|       |-- c
|       +-- e
+-- g
    +-- i
        +-- h
>>> findall(f, filter_=lambda node: node.name in ("a", "b"))
(Node('/f/b'), Node('/f/b/a'))
>>> findall(f, filter_=lambda node: d in node.path)
(Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e'))

When I replicate this exact code in IDLE, I end up with this error:

>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> findall(f, filter_=lambda node: node.name in ("a", "b"))
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    findall(f, filter_=lambda node: node.name in ("a", "b"))
NameError: name 'findall' is not defined

Please let me know if I need to import something else or if there is any other way to search through a tree with anytree.


Solution

  • You have to import the the search module

    from anytree import Node, RenderTree, AsciiStyle, search
    
    result = search.findall(f, filter_=lambda node: node.name in ("a", "b"))
    
    print(result) // (Node('/f/b'), Node('/f/b/a')