Get item from set

Aahz aahz at
Mon Apr 27 18:10:52 CEST 2009

In article <gt1kb7$jqg$03$1 at>,
Peter Otten  <__peter__ at> wrote:
>Here's a trick to find the actual element. I think Raymond Hettinger posted
>an implementation of this idea recently, but I can't find it at the moment.

Your code is inverted from Raymond's:

class _CaptureEq:
    'Object wrapper that remembers "other" for successful equality tests.'
    def __init__(self, obj):
        self.obj = obj
        self.match = None
    def __eq__(self, other):
        result = (self.obj == other)
        if result:
            self.match = other
        return result
    # support hash() or anything else needed by __ contains__
    def __getattr__(self, name):  
        return getattr(self.obj, name)

def get_equivalent(container, item, default=None):
    '''Gets the specific container element matched by: "item in container".

    Useful for retreiving a canonical value equivalent to "item".  For
    example, a caching or interning application may require fetching a
    single representativ e instance from many possible equivalent

    >>> get_equivalent(set([1, 2, 3]), 2.0)       # 2.0 is equivalent to 2
    >>> get_equivalent([1, 2, 3], 4, default=0)
    t = _CaptureEq(item)
    if t in container:
        return t.match
    return default
Aahz (aahz at           <*>

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair

More information about the Python-list mailing list