I just wrote a testing script for a project I have in python, and I learned that checking if the values of two objects are equivalent is not as simple as foo == bar. For example, I have an object dashboard that has a pandas dataframe as an attribute, so I defined it's __eq__ method as:
def __eq__(self, other): vals = [self.__dict__[k] == other.__dict__[k] for k in self.__dict__.keys()] vals = [v if isinstance(v, bool) else all(v) for v in vals] return all(vals)
It compares the dictionaries of each object, and if any of these comparisons yields something other than a boolean (e.g., a dataframe) it applies all() to reduce it to a single boolean. I then apply all() to this entire list of attribute comparisons to test whether or not every attribute of self and other are equivalent.
I used this __eq__ definition in several classes, and also used something similar for a comparison method in my parent Test class. I got my test to work, but I'm curious if there's a more elegant/efficient way to handle this. (Disclaimer: Testing is new to me, as well as OOP in general.)
Aucun commentaire:
Enregistrer un commentaire