Search code examples
pythonanytree

Name not defined when using Anytree class


I am working with Python's anytree package, and I am trying to iterate over the tree:

from anytree import Node, RenderTree, AsciiStyle

f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)

print(RenderTree(f, style=AsciiStyle()).by_attr())


for node in LevelOrderIter(f):
    print node.name

However, for some reason I am getting an error NameError: name 'LevelOrderIter' is not defined.

I have installed anytree (it works creating nodes, etc.) and I seem to be correct according to syntax: http://anytree.readthedocs.io/en/latest/apidoc/anytree.iterators.html#anytree.iterators.LevelOrderIter

Any ideas what it does not work?

Full error:

f
+-- b
    +-- a
Traceback (most recent call last):
  File "aa.py", line 10, in <module>
    for node in LevelOrderIter(f):
NameError: name 'LevelOrderIter' is not defined

Solution

  • If you are calling a function from a library you either call it mentioning the library like anytree.LevelOrderIter() or you can import it directly like this:

    from anytree import LevelOrderIter