adding elements to set

A

Andrea Crotti

I've wasted way too much time for this, which is surely not a Python bug,
not something that surprised me a lot.

I stupidly gave for granted that adding an object to a set would first
check if there are equal elements inside, and then add it.

As shown below this is not clearly the case..
Is it possible to get that behaviour implementing another magic method
in my C class or I just have use another function to check (as I'm doing
now).

class C(object):

def __init__(self, x):
self.x = x

def __eq__(self, other):
return self.x == other.x


if __name__ == '__main__':
s = set()
c1 = C(1)
c2 = C(1)
assert c1 == c2
s.add(c1)
s.add(c2)

print len(s)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top