Boolean tests [was Re: Attack a sacred Python Cow]

Matthew Woodcraft mattheww at chiark.greenend.org.uk
Thu Jul 31 19:51:25 EDT 2008


Steven D'Aprano wrote:
>On Thu, 31 Jul 2008 22:01:48 +0100, Matthew Woodcraft wrote:
>> The point is that if you tell people that "if x" is the standard way to
>> check for emptiness, and also support a general principle along the
>> lines of "write your function using the interfaces you expect, and call
>> it using the object you have", you should expect to end up with bugs of
>> this sort.

> I'm not sure that an occasional performance hit justifies calling it a
> bug. I suppose you might come up with a scenario or two where it really
> is a problem, but then I'm also free to imagine scenarios where calling
> len(obj) takes a massive performance hit, or has irreversible side
> effects.

Of course performance problems can be bugs! And it was explicit in my
example that this was supposed to be such a case.

But here, have an example where it's a non-performance bug:

    def load_widgets(self, widgets):
        if not widgets:
            raise ValueError("no widgets specified")
        self._prepare_for_widgets()
        for widget in widgets:
            self._load_widget(widget)
        self._is_widgetty = True

This way you can end up with an object in an invalid state.


>> I'm not a fan of len() for testing emptiness. But it would have been
>> better in this case, because it would have converted a hard-to-find
>> performance bug into an obvious exception.

> At the cost of wrongly raising a exception for perfectly good arguments,
> namely non-empty iterators.

Sure, which will be fixed when the code passing an iterator is first
tested, whether the iterator is empty or not. It's the errors which pass
silently that are most dangerous.


As I said, I'm not a fan of len() for testing emptiness. But "if x"
isn't good either. Often I end up rearranging things so I can get rid of
the explicit test altogether, but there can be a cost in readability.

I think any Python-like language would be better off with an explicit
way of asking 'is this container empty?'.

-M-




More information about the Python-list mailing list