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

Carl Banks pavlovevidence at gmail.com
Tue Jul 29 17:27:48 EDT 2008


On Jul 29, 3:43 pm, "Heiko Wundram" <modeln... at modelnine.org> wrote:
> Am 29.07.2008, 18:30 Uhr, schrieb Carl Banks <pavlovevide... at gmail.com>:
>
> > On Jul 29, 5:15 am, Heiko Wundram <modeln... at modelnine.org> wrote:
> >> I can't dig up a simple example from code I wrote quickly, but because
> >> of the
> >> fact that explicit comparisons always hamper polymorphism
>
> > I'm not going to take your word for it.  Do you have code that
> > demonstrates how "if x" improves polymorphism relative to simple
> > explicit tests?
>
> As I wrote in the second reply email I sent, check out my integer set
> recipe on ASPN (and to save you the search:  http://code.activestate.com/recipes/466286/).

Couple points:

1. Any container type that returns a length that isn't exactly the
number of elements in it is broken.
2. The need for __nonzero__ in this case depends on a limitation in
the language.
3. On the other hand, I will concede that sometimes calculating len is
a lot more expensive than determining emptiness, and at a basic level
it's important to avoid these costs.  You have found a practical use
case for __nonzero__.

However, I'd like to point out the contrasting example of numpy
arrays.  For numpy arrays, "if x" fails (it raises an exception) but
"if len(x)!=0" succeeds.

The only sane advice for dealing with nonconformant classes like numpy
arrays or your interger set is to be wary of nonconformances and don't
expect polymorphism to work all the time.

So I guess I'll concede that in the occasional cases with
nonconformant classes the "if x" might help increase polymorphism a
little.

(BTW: here's another little thing to think about: the "if x" is useful
here only because there isn't an explicit way to test emptiness
without len.)

Carl Banks



More information about the Python-list mailing list