Get item from set

Peter Otten __peter__ at web.de
Sun Apr 26 08:33:53 EDT 2009


Johannes Bauer wrote:

> I have a very simple about sets. This is a minimal example:

> The problem is: two instances of x() are equal (__eq__ returns true),
> but they are not identical. I have an equal element ("z"), but want to
> get the *actual* element ("a") in the set. I.d. in the above example,
> i'd like something like:
> 
> print(s.getelement(z) is a)
> True
> 
> Is there something like the "getelement" function? How can I do what I
> want?

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.

class X:
    def __init__(self, y):
        self.__y = y
    def __eq__(self, other):
        try:
            return self.__y == other.__y
        except AttributeError:
            return NotImplemented
    def __hash__(self):
        return hash(self.__y)

a = X("foo")
s = set([X("bar"), X("moo"), a])
z = X("foo")

class Grab:
    def __init__(self, value):
        self.search_value = value
    def __hash__(self):
        return hash(self.search_value)
    def __eq__(self, other):
        if self.search_value == other:
            self.actual_value = other
            return True
        return False

assert a == z
assert a is not z
grab = Grab(z)
grab in s
assert grab.actual_value is a

Peter



More information about the Python-list mailing list