Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #16850 > unrolled thread

Re: adding elements to set

Started byPeter Otten <__peter__@web.de>
First post2011-12-08 17:49 +0100
Last post2011-12-08 17:49 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: adding elements to set Peter Otten <__peter__@web.de> - 2011-12-08 17:49 +0100

#16850 — Re: adding elements to set

FromPeter Otten <__peter__@web.de>
Date2011-12-08 17:49 +0100
SubjectRe: adding elements to set
Message-ID<mailman.3432.1323362991.27778.python-list@python.org>
Andrea Crotti wrote:

> 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)

Python's sets are hash-based; you have to implement a __hash__() method for 
the elements that ensures that c1 == c2 implies hash(c1) == hash(c2).

>>> class C(object):                                                  
...     def __init__(self, x): self.x = x
...     def __eq__(self, other): return self.x == other.x
...     def __hash__(self): return hash(self.x)
...
>>> c1 = C(1)
>>> c2 = C(1)
>>> c1 == c2
True
>>> s = set()
>>> s.add(c1)
>>> s.add(c2)
>>> len(s)
1

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web