Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is object() equal to anything besides itself?

Tags:

If I have the code my_object = object() in Python, will my_object be equal to anything except for itself?

I suspect the answer lies in the __eq__ method of the default object returned by object(). What is the implementation of __eq__ for this default object?

EDIT: I'm using Python 2.7, but am also interested in Python 3 answers. Please clarify whether your answer applies to Python 2, 3, or both.

like image 590
Buttons840 Avatar asked May 16 '14 20:05

Buttons840


People also ask

What is object equality in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=

Do Python objects have a value?

Objects are Python's abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann's model of a “stored program computer”, code is also represented by objects.) Every object has an identity, a type and a value.

Is object and string same in Python?

Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings.

What is object in Python?

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. Python is object-oriented programming language that stresses on objects i.e. it mainly emphasizes functions.


1 Answers

object().__eq__ returns the NotImplemented singleton:

print(object().__eq__(3))
NotImplemented

By the reflexive rules of rich comparisons, when NotImplemented is returned, the "reflected" operation is tried. So if you have an object on the RHS that returns True for that comparison, then you can get a True response even though the LHS did not implement the comparison.

class EqualToEverything(object):
    def __eq__(self,other):
        return True

ete = EqualToEverything()

ete == object() # we implemented `ete.__eq__`, so this is obviously True
Out[74]: True

object() == ete # still True due to the reflexive rules of rich comparisons
Out[75]: True

python 2 specific bit: if neither object implements __eq__, then python moves on to check if either implement __cmp__. Equivalent reflexive rules apply here.

class ComparableToEverything(object):
    def __cmp__(self,other):
        return 0

cte = ComparableToEverything()

cte == object()
Out[5]: True

object() == cte
Out[6]: True

__cmp__ is gone in python 3.

In both python 2 and 3, when we exhaust all of these comparison operators and all are NotImplemented, the final fallback is checking identity. (a is b)

like image 193
roippi Avatar answered Oct 16 '22 07:10

roippi