Python checking for None/Null values

Peter Otten __peter__ at web.de
Fri Aug 11 07:17:51 EDT 2006


Fuzzydave wrote:

> Okay, I have been handed a python project and working through it I have
> had to add a report. I am returning 10 variables the results of an SQL
> Query and as usual the number of results vary from 1 result to 10 results
> so I implemented a check to see if the array item was empty or not. The
> code is below based upon the code already in the python project i was
> handed.

In Python list items do not magically spring into existence if you ask for
them. Therefore items[index] raises an IndexError if index is >=
len(items). A possible resolution is to check the length of historyRep
first:

if len(historyRep) > 8 and historyRep[8] is not None:
    history8 = cmi.format_history(historyRep[8])
else:
    history8 = ""

Note that names like history8 are a strong indication that you should use a
list rather than individual variables, e. g:

history = []
for item in historyRep:
    if item is None:
        s = ""
    else:
        s = cmi.format_history(item)
    history.append(s)

or maybe even

history = [cmi.format_history(item) for item in historyRep]

if historyRep doesn't contain any None values.

Peter




More information about the Python-list mailing list