What is being compared?

Ken Seehof kens at sightreader.com
Thu Mar 22 02:05:47 CET 2001


Documentation says:
"""
The operators <, >, ==, >=, <=, and != compare the values of two objects.
The
objects need not have the same type. If both are numbers, they are coverted
to
a common type. Otherwise, objects of different types always compare unequal,
and are ordered consistently but arbitrarily.
"""

I'm pretty sure that the default rules for mixed types are something like
this:
1. numbers are less than non-numbers
2. otherwise compare id(type(a)) with id(type(b))

Note that, rather weirdly, types are compared by their ids.  That's right.
In
other words, the address where the type object happened to get allocated.
Hence the behavior will be only be guaranteed to be consistent within an
execution of the python shell.  On some operating systems it will also
usually
to be mostly consistent from one execution to the next because the objects
tend to be allocated in the same order.

Actually, the documentation is slightly wrong.  Any type can overload
__cmp__
or the new rich comparisons.  Hence it is possible for instances and objects
to
define any inter-type behaviour you want.  In fact the only reason numbers
are
special is that they happen overload __cmp__ to do appropriate conversions.

>>> class God:
...  def __cmp__(self, x):
...     return 0
...
>>> c = God()
>>> c>42
0
>>> c<3
0
>>> c==3
1
>>> c=="spam"
1

----- Original Message -----
From: "Daniel Klein" <DanielK at jBASE.com>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, March 21, 2001 3:59 PM
Subject: What is being compared?


> Comparing a string to an integer...
>
> >>> 'a' < 1
> 0
>
> ..what is it actually comparing? Is it 'casting' anything?
>
> Just curious,
>
> Dan
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>





More information about the Python-list mailing list