Can't get items out of a set?

Raymond Hettinger python at rcn.com
Sat Mar 8 14:15:12 EST 2008


> > > Is it possible to get an object out of a set() given another object
> > > that has the same hash code and equality (__hash__() and __eq__()
> > > return the same)?
>
> > Yes, but it requires an indirect approach.http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299
>
> > Raymond
>
> That's a clever work around.  Thanks, Raymond.  Clearly you had a need
> for this.  Do you feel it's a common need that should be submitted as
> a Python feature request?  To me it seems like such a simple thing
> that would increase the general utility of the set class.  I suppose I
> could start another thread like "feature request: New method for set -
> get_equivalent".

Glad you liked the recipe. :-)  FWIW, it is not specific to sets. The
recipe works with any container including dictionaries and lists.  The
approach is easily extended to any situation with equality testing.
For example, it can be used with list.remove(x) to find the identity
of the removed object.

Long ago, I rejected adding get_equivalent() to the set API.  The
existing API has a near zero learning curve and it would be nice to
keep it that way.

For most use cases, the obvious, explicit approach is better.  Just
make a dictionary where the value is the canonical representative of
the equivalence class:

   >>> d = {1:1, 2:2, 3:3}
   >>> d[2.0]
   2

The intern() builtin uses this approach:

   interned = {}
   def intern(s):
        if s in interned:
            return interned[s]
        interned[s] = s
        return s

Raymond



More information about the Python-list mailing list