473,569 Members | 2,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is up with "=="?

Hello All!

Could someone explain (links are good too!) why:
1+"1" Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +: 'int' and
'str' 1=="1"

0

1 Whos __eq__ or __cmp__ is being called: String's or
Int's?
2 Why IS comparison supported across types?
3 The exception + gives makes it sound like there is
a built-in function + that does not like taking an
'int' and a 'string'. Read this way, the built-in ==
does accept 'int' and 'string'.

Anyway, I have spent a good 10-15 mins googling for
things like 'python subclass int' and have not found
anything useful. (PEP's 252 and 253 did not help me --
perhaps I misread them?)

What am I missing!

Quentin

=====
-- Quentin Crain

------------------------------------------------
I care desperately about what I do.
Do I know what product I'm selling? No.
Do I know what I'm doing today? No.
But I'm here and I'm gonna give it my best shot.
-- Hansel

_______________ _______________ ____
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

Jul 18 '05 #1
5 2920
Quentin Crain wrote:
1 Whos __eq__ or __cmp__ is being called: String's or
Int's?
2 Why IS comparison supported across types?
3 The exception + gives makes it sound like there is
a built-in function + that does not like taking an
'int' and a 'string'. Read this way, the built-in ==
does accept 'int' and 'string'.


It's really a judgement call. It's certainly possible to set up an
equality operator which respects type, but in a dynamic language like
Python, you'll often find yourself comparing objects of different types
for equality. This can get inconvenient, since this means that this
comparisons would raise TypeErrors when all you really care about is
whether or not they're equal or not. Two objects of different types are
obviously unequal (unless __eq__ is deliberately overridden, etc.,
etc.), so it makes sense to simply have == and != not raise TypeErrors.

In fact, it's so common, that if your standard equality operator _does_
raise TypeErrors, you're almost guaranteeing you need another builtin
equality operator which does _not_ respect type. So now you have two
equality operators, which can be confusing -- there's
test-equality-and-raise-if-the-types-are-different and
test-equality-and-treat-different-types-as-simply-unequal. This isn't
necessarily the end of the world, but it's inconvenient. (For the
record, I used this approach -- two equality operators, `eq' and `seq'
-- so I'm not opposed to it on general principle.)

Plus the dynamicism of Python itself enters into it. I can easily come
up with custom classes, whether actually derived from numeric types or
not, which I _do_ want to test equal to existing types. Now it's
looking much more like it would be advantageous for equality to simply
not raise an error on different types and just say, "Nope, they're not
equal."

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ It's a man's world, and you men can have it.
\__/ Katherine Anne Porter
Jul 18 '05 #2
Quentin Crain:
1 Whos __eq__ or __cmp__ is being called: String's or
Int's?
I suspect the int. Does it make a difference?
2 Why IS comparison supported across types?
Historical implementation reasons. There used to be no way for
a comparison to raise an exception. That's changed, but old code
which depended on this hasn't.
3 The exception + gives makes it sound like there is
a built-in function + that does not like taking an
'int' and a 'string'. Read this way, the built-in ==
does accept 'int' and 'string'.


That's an implementation issue I don't know enough about.
Ie, it may be implemented as that even if the implementation
acts identical to one where the tests are done as method of
the type.

Andrew
da***@dalkescie ntific.com
Jul 18 '05 #3

"Quentin Crain" <cz***@yahoo.co m> wrote in message
news:ma******** *************** ***********@pyt hon.org...
2 Why IS comparison supported across types?


There are only two simple rules: only compare within types; allow all
compares. If two things are not equal, why not say so?

Besides history, consider the following intentional feature:
0 == 0L == 0.0 == 0+0j 1 #True in 2.3

One could also import a rational or fixed-point number module and if
their classes have the needed special method, add them to the list.

Also consider this: (0,1,2) == (0,1,'2')

0 # False in 2.3

Would you really want to get an exception rather than False?

Terry J. Reedy
Jul 18 '05 #4
On Wed, 08 Oct 2003 14:29:08 -0700, Erik Max Francis <ma*@alcyone.co m> wrote:
Quentin Crain wrote:
1 Whos __eq__ or __cmp__ is being called: String's or
Int's?
2 Why IS comparison supported across types?
3 The exception + gives makes it sound like there is
a built-in function + that does not like taking an
'int' and a 'string'. Read this way, the built-in ==
does accept 'int' and 'string'.


It's really a judgement call. It's certainly possible to set up an
equality operator which respects type, but in a dynamic language like
Python, you'll often find yourself comparing objects of different types
for equality. This can get inconvenient, since this means that this
comparisons would raise TypeErrors when all you really care about is
whether or not they're equal or not. Two objects of different types are
obviously unequal (unless __eq__ is deliberately overridden, etc.,
etc.), so it makes sense to simply have == and != not raise TypeErrors.

In fact, it's so common, that if your standard equality operator _does_
raise TypeErrors, you're almost guaranteeing you need another builtin
equality operator which does _not_ respect type. So now you have two
equality operators, which can be confusing -- there's
test-equality-and-raise-if-the-types-are-different and
test-equality-and-treat-different-types-as-simply-unequal. This isn't
necessarily the end of the world, but it's inconvenient. (For the
record, I used this approach -- two equality operators, `eq' and `seq'
-- so I'm not opposed to it on general principle.)

Plus the dynamicism of Python itself enters into it. I can easily come
up with custom classes, whether actually derived from numeric types or
not, which I _do_ want to test equal to existing types. Now it's
looking much more like it would be advantageous for equality to simply
not raise an error on different types and just say, "Nope, they're not
equal."

The OP might want to know about type difference NOT implying unequal when
conversion can be done, as between numbers. E.g.,
2==2.0, 2==2L, 2L==2.0 (True, True, True)
BTW, this looks like a bug in the doc<->reality relationship:

Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright" , "credits" or "license" for more information. help(coerce) Help on built-in function coerce:

coerce(...)
coerce(x, y) -> None or (x1, y1)

When x and y can be coerced to values of the same type, return a tuple
containing the coerced values. When they can't be coerced, return None.
coerce(2,'2')

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: number coercion failed

Bad doc string or misimplementati on? Or is it fixed in the latest release, (which I
haven't gotten around to installing yet)?

Regards,
Bengt Richter
Jul 18 '05 #5
On Fri, 10 Oct 2003 11:14:14 -0400, mw*****@the-wire.com (Mel Wilson) wrote:
In article <bm**********@2 16.39.172.122>, bo**@oz.net (Bengt Richter) wrote:
coerce(...)
coerce(x, y) -> None or (x1, y1)

When x and y can be coerced to values of the same type, return a tuple
containing the coerced values. When they can't be coerced, return None.
>>> coerce(2,'2')

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: number coercion failed

Bad doc string or misimplementati on? Or is it fixed in the latest release, (which I
haven't gotten around to installing yet)?


Otherwise, wouldn't it imply that 2+'3' came out to 5 or '23'?

I was referring to the documented "return None" vs. the fact that it raised an exception.

Regards,
Bengt Richter
Jul 18 '05 #6

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

Similar topics

6
16931
by: Ken Varn | last post by:
Sometimes when I try to close my managed C++ application, the following dialog displays in Win 2000 Pro: The title of the dialog is "Server Busy". The message is "This action cannot be completed because the other program is busy. Choose 'Switch to' to activate the busy program and correct the problem." I don't know why this is...
5
2752
by: Jarek | last post by:
Hi all! I'm optimizing my C++ multi-threaded application (linux). My application consumes huge amout of memory from unknown reason. There are no memory leaks, or other allocation bugs, application works well, but on startup it has about 200mb (VmSize). How can I investigate what function/class/other takes so much memory ? I tried to verify...
1
2221
by: blue | last post by:
Looking at code from the following: http://www.gamedev.net/reference/programming/features/enginuity2/page3.asp I'm confused though... CMMPointer(T *o) { obj=0; *this=0;
5
2063
by: junky_fellow | last post by:
Each time i submit some pattern to "google", it shows search took 0.XX seconds for exploring millions of web pages. When i look for efficient ways of searching a string, they always say compare your string with the strings in the file one by one. if there are millions of web pages then these algorithms would take considerable amount of...
2
1484
by: Lasse Edsvik | last post by:
Hello I was wondering if you guys could tell me if: cmd.ExecuteReader(CommandBehavior.CloseConnection); returns a dataset, datatable or what?
1
1831
by: Alan Silver | last post by:
Hello, I have the following line of code in a script... litMsg.Text = Server.MapPath("/"); where litMsg is an ASP.Net Literal control. When I try and run this page, I get the error ... System.ArgumentException: Empty path has no directory.
6
7369
by: MilanB | last post by:
Hello What "0&" means in this function call? ret = InternetQueryOption(0&, INTERNET_OPTION_CONNECTED_STATE, _ ci, ci_len) Thanks Milan
9
4017
by: Dullme | last post by:
i can hardly know what is the code for this. I have researched palindromes, but unfortunately, I only have read about integers not for characters..I need some help..
5
3917
by: cowgurl art | last post by:
Hey there. I will not pretend to know more than I do...I'm just getting my feet wet with Dreamweaver and MySql databases. What I'm trying to do is create a form that will allow members to submit an audio file (mp3 or .wav) from a website. The form will insert the record into the database IF I can get it configured correctly. Here's the...
4
2813
by: CBFalconer | last post by:
regis wrote: Why don't you read the documentation (or source) from whomever supplied you that (non-standard) function? -- : Chuck F (cbfalconer at maineline dot net) : <http://cbfalconer.home.att.net> Try the download section.
0
7700
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7924
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8125
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7676
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7974
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5513
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3642
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.