Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #37697

Retrieving an object from a set

Date 2013-01-25 23:14 +0000
Subject Retrieving an object from a set
From Arnaud Delobelle <arnodel@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1057.1359155683.2939.python-list@python.org> (permalink)

Show all headers | View raw


Dear Pythoneers,

I've got a seemingly simple problem, but for which I cannot find a
simple solution.

I have a set of objects (say S) containing an object which is equal to
a given object (say x). So

    x in S

is true.  So there is an object y in S which is equal to x.  My
problem is how to retrieve y, without going through the whole set.
Here is a simple illustration with tuples (my actual scenario is not
with tuples but with a custom class):

>>> y = (1, 2, 3) # This is the 'hidden object'
>>> S = set([y] + range(10000))
>>> x = (1, 2, 3)
>>> x in S
True
>>> x is y
False

I haven't found y.  It's a very simple problem, and this is the
simplest solution I can think of:

class FindEqual(object):
    def __init__(self, obj):
        self.obj = obj
    def __hash__(self):
        return hash(self.obj)
    def __eq__(self, other):
        equal = self.obj == other
        if equal:
            self.lastequal = other
        return equal

>>> yfinder = FindEqual(x)
>>> yfinder in S
True
>>> yfinder.lastequal is y
True

I've found y!  I'm not happy with this as it really is a trick.  Is
there a cleaner solution?

-- 
Arnaud

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Retrieving an object from a set Arnaud Delobelle <arnodel@gmail.com> - 2013-01-25 23:14 +0000
  Re: Retrieving an object from a set Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-01-26 17:25 +1100

csiph-web