set using alternative hash function?

Diez B. Roggisch deets at nospam.web.de
Thu Oct 15 14:00:55 CEST 2009


Austin Bingham wrote:

> If I understand things correctly, the set class uses hash()
> universally to calculate hash values for its elements. Is there a
> standard way to have set use a different function? Say I've got a
> collection of objects with names. I'd like to create a set of these
> objects where the hashing is done on these names. Using the __hash__
> function seems inelegant because it means I have to settle on one type
> of hashing for these objects all of the time, i.e. I can't create a
> set of them based on a different uniqueness criteria later. I'd like
> to create a set instance that uses, say, 'hash(x.name)' rather than
> 'hash(x)'.
> 
> Is this possible? Am I just thinking about this problem the wrong way?
> Admittedly, I'm coming at this from a C++/STL perspective, so perhaps
> I'm just missing the obvious. Thanks for any help on this.


This is a principal problem in OO - behavior shall not only change based on
the object, but also the context it's used in.

I think the decorator-pattern is the best thing here (in lieu of python
having a hash-argument to sets). Please don't forget to re-define equality
also!

class OtherCriteriaDecorator(object):


   def __init__(self, delegate):
       self._delegate = delegate

   def __hash__(self):
       return hash_based_on_delegate


   def __eq__(self, other):
       return equality_based_on_delegate



HTH,

Diez



More information about the Python-list mailing list