user554319
user554319

Reputation:

Is x==x ever False in Python?

I stumbled upon this line of code in SciPy's source, in the stats module:

return 1.0*(x==x)

Is this return something other than 1.0? In other words, is there any value of x such that x == x holds False?

Upvotes: 8

Views: 417

Answers (3)

bigblind
bigblind

Reputation: 12887

that depends on the value of x. I haven't looked at the source, but let's say you do something like this:

class A:
 def __eq__(self,other):
  return bool(random.getrandbits(1))

x = A()

now x == x may return false.

Upvotes: 3

James
James

Reputation: 3241

A user-defined type can override the equality operator to do whatever you want:

Python 3.2.2 (default, Feb 10 2012, 09:23:17) 
[GCC 4.4.5 20110214 (Red Hat 4.4.5-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...     def __eq__(self, other):
...         return False
... 
>>> x=A()
>>> x==x
False

Upvotes: 9

user1202136
user1202136

Reputation: 11567

According to the IEEE 754 standard not-a-number (NaN) must always compare false, no matter what it is compared to.

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x=float("NaN")
>>> x==x
False

Upvotes: 20

Related Questions