[Python-Dev] Getting values stored inside sets

Hrvoje Niksic hrvoje.niksic at avl.com
Mon Apr 6 13:37:15 CEST 2009


Raymond Hettinger wrote:
>> Hrvoje Niksic wrote:
>>> I've stumbled upon an oddity using sets.  It's trivial to test if a 
>>> value is in the set, but it appears to be impossible to retrieve a 
>>> stored value, 
> 
> See:  http://code.activestate.com/recipes/499299/

Thanks, this is *really* good, the kind of idea that seems perfectly 
obvious once pointed out by someone else.  :-)  I'd still prefer sets to 
get this functionality so they can be used to implement, say, interning, 
but this is good enough for me.

In fact, I can derive from set and add a method similar to that in the 
recipe.  It can be a bit simpler than yours because it only needs to 
support operations needed by sets (__eq__ and __hash__), not arbitrary 
attributes.

class Set(set):
     def find(self, item, default=None):
         capt = _CaptureEq(item)
         if capt in self:
             return capt.match
         return default

class _CaptureEq(object):
     __slots__ = 'obj', 'match'
     def __init__(self, obj):
         self.obj = obj
     def __eq__(self, other):
         eq = (self.obj == other)
         if eq:
             self.match = other
         return eq
     def __hash__(self):
         return hash(self.obj)

 >>> s = Set([1, 2, 3])
 >>> s.find(2.0)
2


More information about the Python-Dev mailing list