type conversions for comparison operators

R

Russ

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)

Now I want to do a test like this:

if object.numItems() > 2: <do something>

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.
 
A

Alex Martelli

Russ said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top