norio
norio

Reputation: 3892

How to retrieve all attributes of an anytree Node?

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.

Upvotes: 1

Views: 1118

Answers (1)

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

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')]

Upvotes: 2

Related Questions