Attack a sacred Python Cow

Terry Reedy tjreedy at udel.edu
Sat Jul 26 17:07:13 EDT 2008



Carl Banks wrote:
> On Jul 24, 4:11 am, Jordan <jordanrastr... at gmail.com> wrote:
>> Of course not.
>>
>> I just think Explicit is better than Implicit is taken seriously by a
>> large segment the Python community as a guiding principle,
> 
> Yeah, try telling that to the people who advise writing "if x" instead
> of "if x==0", or "if s" instead of "if len(s)==0".

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.

What people do properly advise against is the strictly redundant 'if x 
is True' or 'if x == True'.  Both imply a misunderstanding of how 'if' 
works in Python.

As a side note, the usefulness of specific comparisons is greater in 3.0 
where spurious comparisons raise exceptions.  In 3.0, 'if x >= 0' 
specifically means 'if x is a number comparable to ints that is greater 
than or equal to 0'.  In 3.0, [] ==/!= 0 are still False/True, but one 
could exclude incomparables with 'if 0 <= x >= 0' (==0) or 'if x > 0 or 
x < 0' (!=0).  Any such specific comparisons could be used with this 
pattern.

try:
     x = []
     if x >= 0:
         print('should not get here')
except TypeError as m:
     if m.args[0].startswith('unorderable types:'):
         print('Here because of bad comparison')

Terry Jan Reedy




More information about the Python-list mailing list