473,387 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How does compare work?

Hi,

what does Python do if two objects aren't comparable (to my opinion)
If I've understood "Python in a Nutschell" correctly it should raise an
exception but it doesn't do for me.

Here are two examples

if 2 > '1' : print "greater"
else : print "less_or_equal"

prints less_or_equal

and

class C:
def __init__(self): pass

X=C()
if 2 > X : print "greater"

prints greater

In both cases I don't get an exception.
But I'd like to since these lead to hard-to-find bugs.

Thanks for shedding some light on this.

P.S. This is Python 2.4 (CVS)

--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
Jul 18 '05 #1
12 1739

"Helmut Jarausch" <ja******@skynet.be> wrote in message
news:40**********************@news.skynet.be...
what does Python do if two objects aren't comparable (to my opinion)
Sorry, Python does what it does, which is generally to compare any two
objects unless explicitly disabled as with complex numbers or in
user-written method of user class.
If I've understood "Python in a Nutschell" correctly it should raise an
exception but it doesn't do for me.


Perhaps you could quote the line that mislead you, and someone could
explain, or suggest a change to the author.

Terry J. Reedy


Jul 18 '05 #2
On Mon, Jan 26, 2004 at 10:28:31PM +0100, Helmut Jarausch wrote:
Hi,

what does Python do if two objects aren't comparable (to my opinion)
If I've understood "Python in a Nutschell" correctly it should raise an
exception but it doesn't do for me.
From section 5.9 in Python 2.3.3 Reference manual;

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

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in operators.
In the future, the comparison rules for objects of
different types are likely to change.)
"""

-Inyeol Lee

Jul 18 '05 #3
Inyeol Lee wrote:
(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in operators.
In the future, the comparison rules for objects of
different types are likely to change.)
"""


When comparing mixed types becomes illegal, does that mean sorting a
sequence of mixed types becomes illegal as well? Or will sort be a
special case?

yours,
Gerrit.

--
136. If any one leave his house, run away, and then his wife go to
another house, if then he return, and wishes to take his wife back:
because he fled from his home and ran away, the wife of this runaway shall
not return to her husband.
-- 1780 BC, Hammurabi, Code of Law
--
PrePEP: Builtin path type
http://people.nl.linux.org/~gerrit/c.../pep-xxxx.html
Asperger's Syndrome - a personal approach:
http://people.nl.linux.org/~gerrit/english/

Jul 18 '05 #4
On Tue, Jan 27, 2004 at 02:16:51PM +0100, Gerrit Holl wrote:
Inyeol Lee wrote:
(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in operators.
In the future, the comparison rules for objects of
different types are likely to change.)
"""


When comparing mixed types becomes illegal, does that mean sorting a
sequence of mixed types becomes illegal as well? Or will sort be a
special case?


There was discussion of another operation, "before", which could be used
to order different types, but which would not be used by < or >.

I forget if the final word on this idea was positive or negative, but I'm
sure anyone interested could dig up the relevant thread on python-dev.

Jp

Jul 18 '05 #5
Terry Reedy wrote:
"Helmut Jarausch" <ja******@skynet.be> wrote in message
news:40**********************@news.skynet.be...
what does Python do if two objects aren't comparable (to my opinion)

Sorry, Python does what it does, which is generally to compare any two
objects unless explicitly disabled as with complex numbers or in
user-written method of user class.

If I've understood "Python in a Nutschell" correctly it should raise an
exception but it doesn't do for me.

Perhaps you could quote the line that mislead you, and someone could
explain, or suggest a change to the author.


First let me say that IMHO this is a big misdesign of Python.
I've come to Python from Perl since many posts convinced me that Python
is safer - and mostly it is.
But silently(!) comparing apples with pears is evil. E.g. the example I
came across this was

thresh=raw_input('enter threshold')
....
level=2
....
if level > thresh :

which failed miserably. By the way, Perl does convert the string to an
integer silenty and, as most of the time, these Perl conversions are
just what one wants, so here.
Nevertheless, I'd prefer an exception in this case since automatic
conversions can never be right in all circumstances.
So this is a case where Python is a very dangerous language!

For the quotation
In my 'Python in a Nutshell' by Alex Martelli (a tremendously good
book), 1st edition on page 91 (Special Methods) it reads
__cmp__ ......
................
When __cmp__ is also absent, order comparisons (<,<=,>,>=)
raise exceptions. Equality comparisons (==,!=), in this case,
become identity checks: x==y evaluates id(x)==id(y) (i.e.,
x is y)

end of quotation.
I wish this were true for the current Python implementation.

Helmut.

--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
Jul 18 '05 #6
Terry Reedy wrote:
"Helmut Jarausch" <ja******@skynet.be> wrote in message
news:40**********************@news.skynet.be...
what does Python do if two objects aren't comparable (to my opinion)

Sorry, Python does what it does, which is generally to compare any two
objects unless explicitly disabled as with complex numbers or in
user-written method of user class.

If I've understood "Python in a Nutschell" correctly it should raise an
exception but it doesn't do for me.

Perhaps you could quote the line that mislead you, and someone could
explain, or suggest a change to the author.


First let me say that IMHO this is a big misdesign of Python.
I've come to Python from Perl since many posts convinced me that Python
is safer - and mostly it is.
But silently(!) comparing apples with pears is evil. E.g. the example I
came across this was

thresh=raw_input('enter threshold')
....
level=2
....
if level > thresh :

which failed miserably. By the way, Perl does convert the string to an
integer silenty and, as most of the time, these Perl conversions are
just what one wants, so here.
Nevertheless, I'd prefer an exception in this case since automatic
conversions can never be right in all circumstances.
So this is a case where Python is a very dangerous language!

For the quotation
In my 'Python in a Nutshell' by Alex Martelli (a tremendously good
book), 1st edition on page 91 (Special Methods) it reads
__cmp__ ......
................
When __cmp__ is also absent, order comparisons (<,<=,>,>=)
raise exceptions. Equality comparisons (==,!=), in this case,
become identity checks: x==y evaluates id(x)==id(y) (i.e.,
x is y)

end of quotation.
I wish this were true for the current Python implementation.

Helmut.

--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany

Jul 18 '05 #7
In article <40**************@skynet.be>,
Helmut Jarausch <ja******@skynet.be> wrote:

First let me say that IMHO this is a big misdesign of Python.


Guido has come around to this POV. However, being able to compare
different types does have some defensibility. Your example of an ``if``
isn't directly relevant; what's more important is the question of
sorting a list containing arbitrary information. This is particularly
true for the case of something like extracting keys from a dict -- you
don't want an exception raised.

What may well happen is that sort comparisons get a different set of
special methods than relational operators.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code --
not in reams of trivial code that bores the reader to death." --GvR
Jul 18 '05 #8
> But silently(!) comparing apples with pears is evil. E.g. the example I
came across this was

thresh=raw_input('enter threshold')
...
level=2
...
if level > thresh :

which failed miserably. By the way, Perl does convert the string to an
integer silenty and, as most of the time, these Perl conversions are
just what one wants, so here.
Nevertheless, I'd prefer an exception in this case since automatic
conversions can never be right in all circumstances.
So this is a case where Python is a very dangerous language!


The comparison doesn't fail, it succeeds, just not the way you like. If
you want thresh to be an integer, perhaps you should say
thresh = int(raw_input('enter threshold'))

Perhaps one way to alleviate the problem is to have a special kind of
input function:

def special_input(prompt, typ):
a = None
while a is None:
if typ is int:
r = '-?[0-9]+'
#special cases for each kind of input
a = re.search(r, raw_input(prompt))
if a is not None:
return typ(a.group(0))

Maybe a more fully featured set of input functions would be useful to
include in the standard library. Perhaps someone should write an
example module and submit it.

- Josiah
Jul 18 '05 #9
In article <ma**************************************@python.o rg>,
Gerrit Holl <ge****@nl.linux.org> wrote:
Inyeol Lee wrote:
(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in operators.
In the future, the comparison rules for objects of
different types are likely to change.)
"""


When comparing mixed types becomes illegal, does that mean sorting a
sequence of mixed types becomes illegal as well? Or will sort be a
special case?


Presumably there'd be a whole new set of comparisons that
would support inter-type < (e.g. for sorts) and == (e.g. for
dicts). Even then, what about PEP 326, which presumes to
define highest and lowest objects that can be compared with
anything?

Regards. Mel.
Jul 18 '05 #10
In article <eN+FAls/KH*******@the-wire.com>,
Mel Wilson <mw*****@the-wire.com> wrote:

Even then, what about PEP 326, which presumes to define highest and
lowest objects that can be compared with anything?


What about it? ;-)

(Guido just posted a Pronouncement rejecting it.)
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code --
not in reams of trivial code that bores the reader to death." --GvR
Jul 18 '05 #11
Aahz wrote:
In article <eN+FAls/KH*******@the-wire.com>,
Mel Wilson <mw*****@the-wire.com> wrote:
Even then, what about PEP 326, which presumes to define highest and
lowest objects that can be compared with anything?

What about it? ;-)

(Guido just posted a Pronouncement rejecting it.)


When I get around to posting the final version with an example module,
people can still use it if they want.
- Josiah
Jul 18 '05 #12
On Tuesday 27 January 2004 06:44 pm, Helmut Jarausch wrote:
...
In my 'Python in a Nutshell' by Alex Martelli (a tremendously good
book), 1st edition on page 91 (Special Methods) it reads
__cmp__ ......
...............
When __cmp__ is also absent, order comparisons (<,<=,>,>=)
raise exceptions. Equality comparisons (==,!=), in this case,
become identity checks: x==y evaluates id(x)==id(y) (i.e.,
x is y)

end of quotation.
I wish this were true for the current Python implementation.


Thanks for pointing out the error in the first sentence you quote; what the
sentence _should_ say, to describe Python's current implementation, is that
when none of the specific (__lt__ etc) nor generic (__cmp__) methods are
present, comparisons of objects default to comparisons of their id() values.

I apologize for my mistake. Could I ask you to be so kind as to post this
issue to the errata page, http://www.oreilly.com/catalog/pythonian/errata/ ?
By far the best way to get future printings fixed is for a reader to submit
errata, so it goes through the editorial process and comes to me for fixing.

Thanks!
Alex
Jul 18 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then...
3
by: baobaoba | last post by:
The following code compiles on gcc, but cannot be executed. I got some wierd message when executed: 1: Syntax error: ")" unexpected Is there anything wrong in my function template? #include...
8
by: Sivas | last post by:
Hi, Can anyone tell me why this does not work: --------------------------------------------- float b = 2.51F; switch(b) {
2
by: makthar | last post by:
Thanks for taking the time to read this note Can anyone explain what went wrong and any ideas how to fix it I have a search page With three buttons few drop downs and a textbox. The search...
3
by: CyberLotus | last post by:
Hi, I wish to validate the date a user has entered against the format dd-mmm-yyyy using the CompareValidator, but it does not work. Does anybody have a simple solution please? Many thanks...
17
by: Protoman | last post by:
Why does getenv work backwards? When I'm testing an env variable, I have to test if its NOT equal to, rather than equal to, to get the desired result. As evidenced by this simple piece of code: ...
13
by: david ullua | last post by:
Hi, In Expand.c of BSD system, I met the following codes, the expression (column & 07) if used to compare variable column and 7, if column<=7, it returns true, else false. It use (column & 07)...
42
by: Sheldon | last post by:
Hi, This program works when tested with gdb ( see results 1) but when used in a larger program where 12 becomes 1500 there exists a problem when freeing the memory ( see results 2). Can anyone...
9
by: active | last post by:
Can you see why this does not sort the list? It displays OK but is not sorted Thanks for any help
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.