How do I fix "TypeError: Object" NoneType "cannot be decoded" in a recursive function?
def Ancestors (otu,tree):
if tree[otu][0][0] == None:
return []
else:
return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
The problem is that at some point the function tries to call something that is None, this happens instead of the function returning the list I want. I thought the if statement explains this, but it seems like I was wrong. Any advice?
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
Ancestors('A',a)
File "C:\x.py", line 129, in Ancestors
return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
File "C:\x.py", line 129, in Ancestors
return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
File "C:\x.py", line 129, in Ancestors
return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
File "C:\x.py", line 129, in Ancestors
return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
File "C:\x.py", line 126, in Ancestors
if tree[otu][0][0] == None:
TypeError: 'NoneType' object is not subscriptable
This is that tree
{'A': [('AD', 4.0), None, None], 'C': [('ADBFGC', 14.5), None, None], 'B': [('BF', 0.5), None, None], 'E': [('ADBFGCE', 17.0), None, None], 'D': [('AD', 4.0), None, None], 'G': [('BFG', 6.25), None, None], 'F': [('BF', 0.5), None, None], 'ADBFG': [('ADBFGC', 6.25), ('AD', 4.25), ('BFG', 2.0)], 'BF': [('BFG', 5.75), ('B', 0.5), ('F', 0.5)], 'ADBFGC': [('ADBFGCE', 2.5), ('ADBFG', 6.25), ('C', 14.5)], 'ADBFGCE': [None, ('ADBFGC', 2.5), ('E', 17.0)], 'BFG': [('ADBFG', 2.0), ('BF', 5.75), ('G', 6.25)], 'AD': [('ADBFG', 4.25), ('A', 4.0), ('D', 4.0)]}
with otu referring to any of the strings in the tree.
source to share
It simply means that either tree
, tree[otu]
or tree[otu][0]
is evaluated as None
and, as such, cannot be deciphered. Most likely, tree[otu]
or tree[otu][0]
. Track this down with some simple debugging:
def Ancestors (otu,tree):
try:
tree[otu][0][0]
except TypeError:
print otu, tre[otu]
raise
#etc...
or pdb
source to share
One of the values that you pass on Ancestors
, at some point it becomes None
so said, so check to see if otu
, tree
, tree[otu]
or tree[otu][0]
are None
in the beginning of the function instead of checking tree[otu][0][0] == None
. But you might want to reconsider your path and the data type in question to see if you can improve the structure a bit.
source to share