Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python have an __ne__ operator method instead of just __eq__?

The answer here gives a handwaving reference to cases where you'd want __ne__ to return something other than just the logical inverse of __eq__, but I can't imagine any such case. Any examples?

like image 849
Jegschemesch Avatar asked Feb 26 '12 11:02

Jegschemesch


People also ask

What is Python__ eq__?

Summary. Implement the Python __eq__ method to define the equality logic for comparing two objects using the equal operator ( == )

How eq works in Python?

eq() function is a library function of operator module, it is used to perform "equal to operation" on two values and returns True if the first value is equal to the second value, False, otherwise. Parameter(s): x,y – values to be compared.

What is __ GT __ in Python?

__gt__(y) to obtain a return value when comparing two objects using x > y . The return value can be any data type because any value can automatically converted to a Boolean by using the bool() built-in function. If the __gt__() method is not defined, Python will raise a TypeError .

How could you overload the addition operator in the Python language?

To overload an operator + , you need to provide an implementation to a particular special method in your class. Whenever you use + , a special method called __add__ is invoked. Now you can add up two instances of Bill . The + operator invokes the __add__ method, which knows how to add up two instances of Bill .


2 Answers

SQLAlchemy is a great example. For the uninitiated, SQLAlchemy is a ORM and uses Python expression to generate SQL statements. In a expression such as

meta.Session.query(model.Theme).filter(model.Theme.id == model.Vote.post_id) 

the model.Theme.id == model.VoteWarn.post_id does not return a boolean, but a object that eventually produces a SQL query like WHERE theme.id = vote.post_id. The inverse would produce something like WHERE theme.id <> vote.post_id so both methods need to be defined.

like image 147
Jochen Ritzel Avatar answered Oct 18 '22 09:10

Jochen Ritzel


Some libraries do fancy things and don't return a bool from these operations. For example, with numpy:

>>> import numpy as np >>> np.array([1,2,5,4,3,4,5,4,4])==4 array([False, False, False,  True, False,  True, False,  True,  True], dtype=bool) >>> np.array([1,2,5,4,3,4,5,4,4])!=4 array([ True,  True,  True, False,  True, False,  True, False, False], dtype=bool) 

When you compare an array to a single value or another array you get back an array of bools of the results of comparing the corresponding elements. You couldn't do this if x!=y was simply equivalent to not (x==y).

like image 32
Weeble Avatar answered Oct 18 '22 09:10

Weeble