Juan Chô
Juan Chô

Reputation: 572

python set difference on hashable objects

I am a bit disappointed by this, I've defined a class events (which are considered equal if they are close on coordinates and happen at the same date):

import datetime

class Event(object):
    def __init__(self, fixed_date, longitude, latitude):
        self.fixed_date = fixed_date
        self.longitude = longitude
        self.latitude = latitude
        self.tolerance = 0.000044915764206/5 # this is roughly one meter
    def __eq__(self, other):
        if not isinstance(other, Event):
            return False
        return self.fixed_date == other.fixed_date and abs(self.longitude - other.longitude)<self.tolerance and abs(self.latitude - other.latitude)<self.tolerance
    def __ne__(self, other):
        return not self.__eq__(other)
    def __hash__(self):
        return hash((self.fixed_date, round(self.longitude,6), round(self.latitude, 6)))

e1 = Event(datetime.date(2020, 5, 14), 0.1, 0.2)
e2 = Event(datetime.date(2020, 5, 14), 0.1, 0.200001)

Then

e1==e2 #==>true
print(set([e1]) - set([e2])) # ==> {<__main__.Event object at 0x7f5bb5c3d898>}
print(len(set([e1]) - set([e2]))) # ==> 1!!

I of course expected set([e1]) - set([e2]) to be the empty set. How can I achieve my goal og getting the empty set here (len of set difference == 1).

Upvotes: 0

Views: 158

Answers (1)

Kemp
Kemp

Reputation: 3649

Your objects are different based on their hashes, so the set operations are doing the correct thing. Specifically, round(0.200001, 6) == 0.200001. Setting the rounding to 5 or the value to 0.2000001 does what you were expecting.

Upvotes: 1

Related Questions