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

Steven D'Aprano steve at
Tue Jul 29 02:15:08 CEST 2008

On Mon, 28 Jul 2008 13:22:37 -0700, Carl Banks wrote:

> On Jul 28, 10:00 am, Steven D'Aprano <st... at REMOVE-THIS-
>> wrote:
>> 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?
> Use case, please.  I'm asking for code, not arguments.  Please give me a
> piece of code where you can write "if x" that works but a simple
> explicit test won't.

I gave you a piece of code, actual code from one of my own projects. If 
you wouldn't accept that evidence then, why would you accept it now?

It isn't that explicit tests will fail, it is that explicit tests are 
more work for no benefit. You keep talking about "simple explicit tests", 
but it seems to me that you're missing something absolutely fundamental: 
"if x" is simpler than "if x!=0" and significantly simpler than "if len
(x)!=0". Even if you discount the evidence of the character lengths (4 
versus 7 versus 12) just use the dis module to see what those expressions 
are compiled into. Or use timeit to see the execution speed.

So I'm not really sure what your point is. Yes, for vast amounts of code, 
there's no *need* to write "if x". If x is always a number, you can 
replace it with "if x != 0" and it will still work. Big deal. I never 
said differently. But if I don't care what type x is, why should I write 
code that cares what type x is?

All you're doing is writing an expression that does more work than it 
needs to. Although the amount of work is trivial for built-ins, it's 
still more than necessary. But provided x is always the right sort of 
duck, your code will work. It will be longer, more verbose, slower, fail 
in unexpected ways if x is an unexpected type, and it goes against the 
spirit of duck-typing, but it will work.


More information about the Python-list mailing list