Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #16849 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2011-12-09 03:47 +1100 |
| Last post | 2011-12-09 03:47 +1100 |
| 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.
Re: adding elements to set Chris Angelico <rosuav@gmail.com> - 2011-12-09 03:47 +1100
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2011-12-09 03:47 +1100 |
| Subject | Re: adding elements to set |
| Message-ID | <mailman.3431.1323362848.27778.python-list@python.org> |
On Fri, Dec 9, 2011 at 3:34 AM, Andrea Crotti <andrea.crotti.0@gmail.com> 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.
It checks for equality using hashes. By default, in Python 2, objects'
hashes are their ids - meaning that no two of them hash alike, and
you'll get duplicates in your set. (In Python 3, the default appears
to be that they're unhashable and hence can't go into the set at all.)
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)
This chains the hashing requirement to the child, just as it chains
the equality check. You can then stuff your objects into a set with
more expected results.
ChrisA
Back to top | Article view | comp.lang.python
csiph-web