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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jul 28 16:00:49 CEST 2008


Cutting to the crux of the discussion...

On Sun, 27 Jul 2008 23:45:26 -0700, Carl Banks wrote:

> I want something where "if x" will do but a simple explicit test won't.

Explicit tests aren't simple unless you know what type x is. If x could 
be of any type, you can't write a simple test. Does x have a length? Is 
it a number? Maybe it's a fixed-length circular length, and the length is 
non-zero even when it's empty? Who knows? How many cases do you need to 
consider?

Explicit tests are not necessarily simple for custom classes. Testing for 
emptiness could be arbitrarily complex. That's why we have __nonzero__, 
so you don't have to fill your code with complex expressions like (say)

if len(x.method()[x.attribute]) > -1

Instead you write it once, in the __nonzero__ method, and never need to 
think about it again.

In general, you should write "if x" instead of an explicit test whenever 
you care whether or not x is something (true), as opposed to nothing 
(false), but you don't care what the type-specific definition of 
something vs. nothing actually is.

To put it another way... using "if x" is just a form of duck-typing. Let 
the object decide itself whether it is something or nothing.


-- 
Steven



More information about the Python-list mailing list