Exception handling and continuing with a for loop in python

272 views Asked by At

I have the following code:

import Bio
from bioservices import KEGGParser, UniProt, QuickGO

#start a new method of my custom 'Retrieve_Data' class
def locate_common_GO(self,list_of_genes,GO_term):
    
    #initialize variables and classes
    q = QuickGO()
    a = Retrieve_Data()
    b=[]

Get the uniprot IDS using (custom method) hugo2uniprot

for i in range(0,len(list_of_genes)):
    b.append(a.hugo2uniprot(list_of_genes[i],'hsa'))
    print 'Gene: {} \t UniProtID: {}'.format(list_of_genes[i],b[i])
    

Search for GO terms (using bioservices' QuickGO) and store as dictionary

GO_dict = {}
q = QuickGO()

Some of the large list of gene names that I have do not return any hits. These cause an AttributeError that I want to handle then move on to the next item in the list. The current code returns the error:

AttributeError: 'int' object has no attribute 'split'.

The error originates within the bioservices module (so when I'm calling q.Annotation)

for i in range(len(b)):
    try:
        GO_dict[list_of_genes[i]] = q.Annotation(protein=b[i], frmt="tsv", _with=True,tax=9606, source="UniProt", col="goName")
    except AttributeError:
        continue

# The rest of this code is irrelevant to my problem but I've included it for completeness: 
# Essentially it is designed to locate specific keywords in the results of the above code and return the gene name that they came from. 
keys = GO_dict.keys()
matches = []
for gene in range(0,len(keys)):
    if GO_term in GO_dict[keys[gene]].splitlines():
        matches.append(keys[gene])
return matches

Does anybody have any suggestions to get the exception handling working so it finishes iterating over the specified list instead of halting the script?

1

There are 1 answers

0
CiaranWelsh On

Okay I've just realized that the problem is that the error was coming from a different bit of code... So I was essentially trying to handle nothing. I've fixed it now, thanks to all those who responded.