What's the tidy/elegant way to protect this against null/empty parameters?

Roy Smith roy at panix.com
Mon Oct 15 08:00:11 EDT 2012


In article <1b8tk9-un9.ln1 at chris.zbmc.eu>, tinnews at isbd.co.uk wrote:

> The function producing the error is:-
> 
>     def get_text(self, idx):               # override !
>         node = self.items[idx]
> 
>         a= [
>             ", ".join(node.tags),
>             node.comment,
>             node.folderName,
>             cd2rd(node.date),
>             node.name,
>             '[' + self.rating_stars[node.rating] + ']'
>             ] [self.select]
> 
>         return a
> 
> 
> The error occurs when node[] (or at least its members) turn out to be
> empty, you get a Traceback that ends with:-
> 
>   File "/usr/lib/jbrout/jbrout/listview.py", line 608, in draw_cell 
>   layout.set_text(self.get_text(thumbnail_num))
>   File "/usr/lib/jbrout/jbrout.py", line 325, in get_text ", 
>   ".join(node.tags),
>   TypeError: sequence item 0: expected string, NoneType found
> 
> Now its *probably* something higher up the tree causing the problem
> (it's only one particular image in 20 thousand or so that breaks
> things) but I really want to just get things working.  So, what's the
> neatest way to protect the get_text() method from empty data?

Well, you don't describe what get_text() is supposed to return  First, 
you build a list of what I'm guessing are all strings, then you index 
into it and return one of the values.  So, I'm guessing get_text() is 
supposed to return a string.

At a low level, you can certainly fix that by testing to see if 
self.items[idx] returns what you're expecting (an instance of Node?) and 
returning an empty string if it's not:

>     def get_text(self, idx):               # override !
>         node = self.items[idx]
>         if not node:
>             return ""
> 
>         a= [
>             ", ".join(node.tags),
>             node.comment,
>             node.folderName,
>             cd2rd(node.date),
>             node.name,
>             '[' + self.rating_stars[node.rating] + ']'
>             ] [self.select]
> 
>         return a

Whether that makes sense in your program, I have no idea.  What does it 
mean for node to be empty?  Is this a normal occurrence?  If so, then 
your code needs to deal with properly (the suggest above being just one 
possible way).

Or, is it "impossible" for node to be empty?  In that case, that fact 
that it *is* empty is a bug, and the above suggestion will just hide the 
bug for one more level and make it that much harder to figure out what's 
really going on.  What you might really want to do is sprinkle your code 
with "assert node" statements.  This will force your program to crash 
and burn the first time node is empty, which might help you figure out 
why it is.



More information about the Python-list mailing list