type conversions for comparison operators

Alex Martelli aleax at mac.com
Wed Jul 18 22:38:01 EDT 2007


Russ <uymqlp502 at sneakemail.com> wrote:

> I recently discovered a bug in one of my programs that surprised me
> because I thought Python's dynamic type checking would have
> caught it.
> 
> Suppose I have a function that returns an integer, such as
> 
> def numItems: return len(self.items)

Syntax errors (you need parentheses before the colon).

> Now I want to do a test like this:
> 
> if object.numItems() > 2: <do something>

Attribute error (unless you've set that numItems "function" to be a
_method_ of the class of "object" AND added a "self" argument).


> But suppose I mistakenly leave off the parentheses:
> 
> if object.numItems > 2: <do something>
> 
> I would have thought that Python would choke on this, but it
> doesn't. Apparently, Python converts the operands to a common
> type, but that seems risky to me. Is there a good reason for allowing
> a function to be compared to an integer? Thanks.

It lets you sort a heterogeneous list which may include objects of many
types (and no "conversion to a common type" is involved, btw).

However, Guido's decided that Python 3.0 will not allow heterogeneous
order-comparisons any more (they can't be removed in 2.* without
breaking backwards compatibility -- 3.0 is allowed to break backwards
compatibility, but 2.* isn't).


Alex



More information about the Python-list mailing list