1

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.

2 Answers2

2

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')
JustCarlos
  • 128
  • 7
0

You have not imported that function. A solution could be to add an import for that function

from anytree import Node, RenderTree, AsciiStyle, findall

or you could import everything from that module with

from anytree import *
f = Node("f")
findall(f, ...)

or you can import the module like this, however you would need to add anytree. in front of everything from that module

import anytree
f = anytree.Node("f")
anytree.findall(f)
sommervold
  • 301
  • 2
  • 8