set using alternative hash function?

Austin Bingham austin.bingham at gmail.com
Thu Oct 15 15:22:22 CEST 2009


On Thu, Oct 15, 2009 at 3:02 PM, Diez B. Roggisch <deets at nospam.web.de> wrote:
> Austin Bingham wrote:
> You do. Hashes can collide, and then you need equality. Sets are *based* on
> equality actually, the hash is just one optimization. ...

Right, thanks for clearing that up. Not reading closely enough ==
public shaming ;)

> Because these functions need intimate knowledge of the objects to actually
> work. Sure, in python it's easy to define them outside, and just reach into
> the object as you wish. But aside this implementation detail, a hash (and
> equality of course) always are based upon the object in question. So I
> think it's natural to have it defined right there (which __hash__ and
> __eq__ show that this seems to be accepted in general).
>
> And if there were something that would decide on context which of several
> implementations to use, you'd have less to worry. As things are, there
> isn't such thing (I don't even have the slightest idea what could work),
> you are as well off with defining two functions.

But this "context decider" you're talking about sounds exactly like
what I'm talking about.  If I had some class with __hash1__ and
__hash2__ (and associated equality operators), you're saying it would
be nice to be able to select which to use based on the context (e.g.
what type of set I'm using.) It might look like this:

   s = set(hash_func = lambda x: x.__hash2__, eq_func = lambda x, y:
x.__eq2__(y))

And if *that* works for you, do you still have a problem with:

  s = set(hash_func = lambda x: hash(x.name), eq_func = lambda x,y:
x.name == y.name)

?

If you don't like those, what would work for you? As far as I can
tell, your "context decider" and my "alternative hash functions" are
the same thing, and we just need to agree on a syntax.



More information about the Python-list mailing list