Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality in dunder method

Tags:

python

I'd like to compare two objects of the same type with the dunder method _eq_ for equality. Every object stores values for "word", "pronunciation", "weight", and "source" and equality is reached, when everything is the same. My solution looks like the following and works but it feels clunky and I am sure that there is a better way.

    def __eq__(self, other):
        if self.check_other(other): # checks of both objects are snstances of LexicalEntity
            return_bool = True
            if self.word != other.get_word():
                return_bool = False
            if self.weight != other.get_weight():
                return_bool = False
            if self.source != other.get_source():
                return_bool = False
            if self.pron != other.get_pron():
                return_bool = False
            return return_bool

Thanks for your help.

like image 790
Scrottz Avatar asked Jun 17 '26 23:06

Scrottz


1 Answers

For starters, dispense with getters and setters in Python. That will make your code much less clunky and more idiomatic, i.e., you don't need other.get_word(), you just need other.word, and remove your definition of get_word, it is useless. Python != Java.

So, then for something like this, a typical implementation would be:

def __eq__(self, other):
    if isinstance(other, LexicalEntity):
        these_values = self.word, self.weight, self.source, self.pron
        other_values = other.word, other.weight, other.source, other.pron
        return these_values == other_values
    return NotImplemented # important, you don't want to return None 
        

Alternatively, you might also just use one long boolean expression:

def __eq__(self, other):
    if isinstance(other, LexicalEntity):
        return (
            self.word == other.word and self.weight == other.weight
            and self.source == other.source and self.pron == other.pron
        )
    return NotImplemented
like image 123
juanpa.arrivillaga Avatar answered Jun 20 '26 12:06

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!