Use getattr third argument to set various default values:
def __eq__(self, other): return all(getattr(self, a, Ellipsis) == getattr(other, a, Ellipsis) for a in self.metainfo)
Set the default value to a value that will never be the actual value, such as Ellipsis & dagger; . Thus, the values โโwill correspond only if both objects contain the same value for a specific attribute or if both of them do not have a specified attribute.
Edit : as Nadia points out NotImplemented might be a more appropriate constant (if you don't save the result of rich comparisons ...).
Edit 2: In fact, as Lac points out, just using hasattr leads to a more readable solution:
def __eq__(self, other): return all(hasattr(self, a) == hasattr(other, a) and getattr(self, a) == getattr(other, a) for a in self.metainfo)
& dagger; : for additional ambiguity you can write ... instead of Ellipsis , thus getattr(self, a, ...) etc. No, do not do this :)
source share