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

Matthew Fitzgibbons elessar at nienna.org
Fri Aug 1 08:28:09 EDT 2008


Antoon Pardon wrote:
> On 2008-08-01, Erik Max Francis <max at alcyone.com> wrote:
>> Antoon Pardon wrote:
>>
>>> I now have the following question for people who argue that "if x"
>>> is more polymorphic. I could subclass list, so that instances
>>> of this new sequence would always behave as true, even if they are
>>> empty.  I could then rewrite my loop as follows:
>>>
>>> while 1:
>>>   extra = produce()
>>>   if not extra:
>>>     break
>>>   for el in extra:
>>>     adjust_with(el)
>>>   calculate()
>>>
>>> Is this second loop now more polymorphic as the first?
>> It's more confusing since you've changed the standard behavior of a 
>> standard type, which doesn't really have anything to do with 
>> polymorphism.  It's more confusing, if that's a benefit.
> 
> So you accept my point that "if x" can be less polymorphic
> and in fact can be more confusing than a more specific test.
> 

I think your example is more related to a trap with polymorphism in 
general rather than an argument against 'is x' specifically. Any time 
you override a method, you have an opportunity to change the behavior in 
unexpected ways. Especially in languages like Python that don't do type 
checking. For example, you write a __cmp__ method like this:

class ReallyBadPractice(object):
     def __cmp__(self, other):
         return -cmp(self, other)

Of course any code that does comparisons on this class is going to 
behave unexpectedly!

-Matt



More information about the Python-list mailing list