set using alternative hash function?

Austin Bingham austin.bingham at gmail.com
Thu Oct 15 12:11:00 EDT 2009


On Thu, Oct 15, 2009 at 5:15 PM, Gabriel Genellina
<gagsl-py2 at yahoo.com.ar> wrote:
> En Thu, 15 Oct 2009 11:42:20 -0300, Austin Bingham
> <austin.bingham at gmail.com> escribió:
> I think you didn't understand correctly Anthony Tolle's suggestion:
>
> py> class Foo:
> ...   def __init__(self, name): self.name = name
> ...
> py> objs = [Foo('Joe'), Foo('Jim'), Foo('Tom'), Foo('Jim')]
> py> objs

I understand Anthony perfectly. Yes, I can construct a dict as you
specify, where all of the keys map to values with name attributes
equal to the key. My point is that dict doesn't really help me enforce
that beyond simply letting me set it up; it doesn't care about the
values at all, just the keys. All that I'm asking for, and I think
it's been made pretty clear, is a set that let's me define a
uniqueness criteria function other than hash(). As has been thrashed
out already, this is not as straightforward as I might have liked.

To put it in code, I want this:

  s = set(hash_func = lambda obj: hash(obj.name), eq_func = ...)
  ...
  x.name = 'foo'
  y.name = 'foo'
  s.add(x)
  s.add(y) # no-op because of uniqueness criteria
  assert len(s) == 1

Austin



More information about the Python-list mailing list