Attack a sacred Python Cow

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Jul 27 05:14:26 EDT 2008


On Sat, 26 Jul 2008 15:58:16 -0700, Carl Banks wrote:

> On Jul 26, 5:07 pm, Terry Reedy <tjre... at udel.edu> wrote:
>> Whether or not one should write 'if x' or 'if x != 0' [typo corrected]
>> depends on whether one means the general 'if x is any non-null object
>> for which bool(x) == True' or the specific 'if x is anything other than
>> numeric zero'.  The two are not equivalent.  Ditto for the length
>> example.
> 
> Can you think of any use cases for the former?  And I mean something
> where it can't be boiled down to a simple explicit test for the sorts of
> arguments you're expecting; something that really takes advantage of the
> "all objects are either true or false" paradigm.

But why do you need the explicit test? What benefit do you get from 

if len(alist) != 0

instead of the simpler and faster "if alist" ? If you need to know that 
alist is actually a list, isinstance() is the function you want; and if 
you want to know that it has a length, hasattr(alist, '__len__') is 
better. (Or call len() in a try...except block.) Either way, testing the 
length is zero explicitly gains you nothing, and risks failure for any 
sequence types that might distinguish between an empty sequence and a 
length of zero.


> The best thing I can come up with out of my mind is cases where you want
> to check for zero or an empty sequence, and you want to accept None as
> an alternative negative as well.  But that's pretty weak.

You might find it pretty weak, but I find it a wonderful, powerful 
feature.

I recently wrote a method that sequentially calls one function after 
another with the same argument, looking for the first function that 
claims a match by returning a non-false result. It looked something like 
this:

def match(arg, *functions):
    for func in functions:
        if func(arg):
            return func

I wanted the function itself, not the result of calling the function. I 
didn't care what the result was, only that it was something (indicates a 
match) or nothing (no match). In one application, the functions might 
return integers or floats; in another they might return strings. In a 
third, they might return re match objects or None. I don't need to care, 
because my code doesn't make any assumptions about the type of the result.


-- 
Steven



More information about the Python-list mailing list