How safe is a set of floats?

Paul McGuire ptmcg at austin.rr.com
Fri May 4 13:15:57 EDT 2007


On May 4, 11:50 am, Arnaud Delobelle <arno... at googlemail.com> wrote:
> On May 4, 5:04 pm, Paul McGuire <p... at austin.rr.com> wrote:
>
> > Does set membership test for equality ("==") or identity ("is")?  I
> > just did some simple class tests, and it looks like sets test for
> > identity.
>
> Sets are like dictionaries, they test for equality:
>
> >>> a=1,2
> >>> b=1,2
> >>> a is b
> False
> >>> a in set([b])
>
> True
>
> --
> Arnaud

Just to beat this into the ground, "test for equality" appears to be
implemented as "test for equality of hashes".  So if you want to
implement a class for the purposes of set membership, you must
implement a suitable __hash__ method.  It is not sufficient to
implement __cmp__ or __eq__, which I assumed "test for equality" would
make use of.  Not having a __hash__ method in my original class caused
my initial confusion.

So would you suggest that any class implemented in a general-purpose
class library should implement __hash__, since one cannot anticipate
when a user might want to insert class instances into a set?  (It
certainly is not on my current checklist of methods to add to well-
behaved classes.)


-- Paul






More information about the Python-list mailing list