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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Jul 29 02:23:02 CEST 2008


On Tue, 29 Jul 2008 01:19:00 +0200, Anders J. Munch wrote:

> Steven D'Aprano wrote:
>> 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 you don't even know a duck-type for x, you have no business invoking
> any methods on that object.

Have you tried to make "if x" fail?

Pull open an interactive interpreter session and try. You might learn 
something.

 
> If you do know a duck-type for x, then you also know which explicit test
> to perform.
> 
>> 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.
> 
> Okay, so you have this interesting object property that you often need
> to test for, so you wrap the code for the test up in a method, because
> that way you only need to write the complex formula once.  I'm with you
> so far.  But then you decide to name the method "__nonzero__", instead
> of some nice descriptive name?
>   What's up with that?

Dude. Dude. Just... learn some Python before you embarrass yourself 
further.

http://www.python.org/doc/ref/customization.html




-- 
Steven



More information about the Python-list mailing list