comparing strings and ints

Randall Hopper aa8vb at
Tue Apr 11 19:43:58 CEST 2000

Fredrik Lundh:
 |Mark H.H. Montague wrote:
 |> Does anyone know why it is not a type error to compare a string and an
 |> int with '>' ?  For example, I just spent over an hour debugging code
 |> that essentially did this:
 |> >>> 45 > '0'
 |> 0
 |> Of course, the '0' was a variable read in from a file, which I forgot
 |> to convert to a string.  Bad old perl habits.  But I'm having a hard
 |> time imagining a situation where someone would be intentionally and
 |> meaningfully comparing a string and an int.
 |> Any ideas?
 |why not read the fine documentation:

I suspect many folks consult it first, but (though excellent on most
topics) occasionally it's difficult to find what you want.  And sometimes
(rarely) if and when you find the topic, the behavior doesn't "seem" to
make much sense at first glance.  Thus prompting a question to the group.

(An example is the % operator.  It's an operator so it's in the language
ref manual, right?  No, not exactly.  If you don't think "string method"
you'll never find it.  Compare to +/-.  Why is it special?  Beats me.)

 |which explains that:
 |    Objects of different types always compare unequal,
 |    and are ordered consistently but arbitrarily.

Reminds me of qsort() core dumps because the compiled C library compared
NaNs and Infs arbitrarily.

I can see 45 == '45' being false, and 45 != '45' being true.  But it seems
to me that not throwing an exception for attempts at an ordered comparison
with logical ordering operators (<, <=, etc.) on objects of different
primitive types (e.g. 45 < '45', 45 > '45') only lets bugs pass through.

Is there a case where this could be useful (with its undefined behavior)?
I believe that is the root of the question.
 |    This unusual definition of comparison was used to
 |    simplify the definition of operations like sorting and
 |    the "in" and "not in" operators.

== and != seems to cover "in"/"not in".  In what context is sorting done
on instances that have different primitive types?

 |and goes on to say:
 |    In the future, the comparison rules for objects of
 |    different types are likely to change.

Possibly making ording operations illegal in this case (?)

Randall Hopper
aa8vb at

More information about the Python-list mailing list