How to retrieve all attributes of an anytree Node?

Question:

For an anytree Node, how can I get all the attributes and their values?

For example, if I do:

>>> from anytree import Node
>>> root = Node("root")
>>> s0 = Node("sub0", parent=root, foo="10", bar="ggg")

how can I get something like [("foo", "10"), ("bar", "ggg")]?

I can think of a route via the following:

>>> s1=Node("dummy", parent=root)
>>> set(dir(s0))-set(dir(s1))
{'foo', 'bar'}

but I hope there is a more concise way.

Asked By: norio

||

Answers:

This is working in your case:

s0.__dict__.items()

However, beware that this method relies on the inner implementation of anytree (and it’s always a bad idea to rely on a specific implementation). Also, the __dict__ attribute contains also the name, parent and (optionally) children (and you might want to get rid of these).

[(k, v) for k, v in s0.__dict__.items() if k not in ('name', 'parent', 'children')]
Answered By: Riccardo Bucco
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.