Python avoid item = None in a request of multiple items

73 views Asked by At

I'm doing a loop for multiple requests on a web database, each time it takes one geneId to request it to the database. If the geneId is referenced I can use the data I get for another request on a second database. But if the geneId is not referenced, it gives me nothing back and it destroys my functions. So I determined a None possibility, but in this case I'm getting a :

TypeError: 'NoneType' object is not iterable.

here is a part of my code with the None :

def getNewID(oneGeneIdAtOnce):
url = "http:/blablabla"
try :
    cookieJar = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookieJar))
    opener.addheaders = getHeaders()
    resp = opener.open(url)
    data = urllib.parse.urlencode(getPost(oneGeneIdAtOnce))
    data = data.encode("UTF-8")
    resp = opener.open(url, data)
    respData = resp.read()
    jobValue = getJobValueFromCookie(cookieJar)
    downloadUrl = getUrlFromJobValue(jobValue)
    resp = opener.open(downloadUrl)
    respData = resp.read()          
    string = respData.decode("UTF-8")
    if not string:
        return None
    l = string.split("\n")
    lFinal = l[1].split("\t")       
    return lFinal[1]
except HTTPError as httpError:
    print("HERE     " + str(httpError))
except TypeError:
    None


def searchGoFromDico(dictionary):   
dicoGoForEachGroup = {}
for groupName in dico:
    taxonAndGene = dico[groupName]          
    listeAllGoForOneGroup = []      
    for taxon in taxonAndGene:          
        geneIds = taxonAndGene[taxon]           
        for geneId in geneIds:                      
            if geneId is not None:                                  
                listeGo = getGoID(getUniprotID(geneId))                                             
                listeAllGoForOneGroup.extend(listeGo)               
    dicoGoForEachGroup[groupName] = listeAllGoForOneGroup                                                   
return dicoGoForEachGroup

Any idea to allow my functions to work properly even if one of the geneId is None for the database ? Thank you for your upcoming answers.

1

There are 1 answers

0
stevieb On BEST ANSWER

You can use a try/except block around the code that's causing the issue. If the list is empty, run the next iteration of the outer for loop (untested):

def searchGoFromDico(dictionary):
dicoGoForEachGroup = {}
for groupName in dico:
    taxonAndGene = dico[groupName]
    listeAllGoForOneGroup = []
    for taxon in taxonAndGene:
        geneIds = taxonAndGene[taxon]
        try:
            for geneId in geneIds:
                if geneId is not None:
                    listeGo = getGoID(getUniprotID(geneId))
                    listeAllGoForOneGroup.extend(listeGo)
        except TypeError:
            continue

    dicoGoForEachGroup[groupName] = listeAllGoForOneGroup
return dicoGoForEachGroup