I have a Thing
class with an float x
attribute. And I want to approximately compare two instances of Thing
with a relelative tolerance of 1e-5.
import attr
@attr.s
class Thing(object):
x: float = attr.ib()
>>> assert Thing(3.141592) == Thing(3.1415926535) # I want this to be true with a relelative tolerance of 1e-5
False
Do I need to override the __eq__
method or is there a clean way of telling attr
to use math.isclose()
or a custom comparison function?
Yes, setting eq=True
and implementing your own __eq__
/__ne__
is your way to go. In this case your need is so specific that I wouldn't even know how to abstract it away without making it confusing.