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

Chris Rebert clp2 at rebertia.com
Mon Oct 15 07:58:24 EDT 2012


On Mon, Oct 15, 2012 at 4:23 AM,  <tinnews at isbd.co.uk> wrote:
> I want to fix an error in some code I have installed, however I don't
> really want to just bodge it.

"bodge". Well, I learned a new word this morning!

> 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,

To be precise: when node.tags contains one or more `None`s (Python's
equivalent of what other languages call "null" or "nil").
That's what the traceback is saying.

> 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))

Ah, so this is apparently regarding https://code.google.com/p/jbrout/
. Would have been nice not to have had to search and then only locate
it indirectly. Something to consider next time you write in...
Make sure you report your bug upstream!

>   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?

Filter out the `None`s with a generator expression:
    ", ".join(tag for tag in node.tags if tag is not None),

Cheers,
Chris



More information about the Python-list mailing list