python ete2 TreeNode check if it has attribute

480 views Asked by At

I have a tree t which some of its nodes has an attribute 'a' I want to test if a given node has this attribute, what I did is

if not n.a:
   print "no a " 

but I'm getting an error treenode n has no attribute a

Any way to test it ?

1

There are 1 answers

0
jhc On BEST ANSWER

You could just use the generic pythonic way

if not hasattr(node, "a"): 
   print "a attribute not found in node:", node

If "a" is registered as a regular feature in your ETE tree, you could also use the following approach:

from ete2 import Tree
t = Tree()
t.populate(5)
t.children[0].add_features(a = "My annotation")

for node in t.traverse():
    if "a" in node.features:
        print node.get_ascii(attributes=["a", "name"])

which would print something like this:

                     /-aaaaaaaaac
-My annotation, NoName
                    |      /-aaaaaaaaad
                     \NoName
                           \-aaaaaaaaae