Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my object properly removed from a list when __eq__ isn't being called?

I have the following code, which is making me scratch my head -

class Element:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

def eq(self, other):
    print('comparing {} to {} ({})'.format(self.name, 
        other.name, 
        self.name == other.name))

    return self.name == other.name

Element.__eq__ = eq
elements = [
    Element('a'), 
    Element('b'), 
    Element('c'), 
    Element('d')    
]

print('before {}'.format(elements))
elements.remove(elements[3])
print('after {}'.format(elements))

Which yields the following output -

before [a, b, c, d]
comparing a to d (False)
comparing b to d (False)
comparing c to d (False)
after [a, b, c]

Why isn't eq() outputting comparing d to d (True)?

The reason I'm monkey patching __eq__ instead of simply implementing it in my Element class is because I'm testing how monkey patching works before I implement it with one of the libraries I'm using.

like image 910
self. Avatar asked Oct 22 '14 14:10

self.


People also ask

What is the __ eq __ method in Python?

Python automatically calls the __eq__ method of a class when you use the == operator to compare the instances of the class.

Are there other special Python methods that you can use to do equality comparison?

Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.

How do you compare two methods 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 != , except when you're comparing to None .

What is other in Python?

other is nothing but an argument name. You can call it whatever you want, although methods obey some conventions to make the code clearer. Here are some argument names that usually have a special meaning. self : an argument expected to be the instance from which the method was called.


1 Answers

The fourth element is the exactly same object with the object the code is passing (elements[3]).

In other word,

>>> elements[3] is elements[3]
True
>>> elements[3] == elements[3]
True

So, no need to check the equality because they(?) are identical (same) one.

Equality check will happen if they are not identical. For example, __eq__ will be called if the code passes another object with the same value:

elements.remove(Element('d'))
like image 191
falsetru Avatar answered Oct 12 '22 15:10

falsetru