[Python-Dev] Getting values stored inside sets

Paul Moore p.f.moore at gmail.com
Fri Apr 3 14:22:02 CEST 2009


2009年4月3日 Hrvoje Niksic <hrvoje.niksic at avl.com>:
> 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,
> other than by iterating over the whole set.  Let me describe a concrete use
> case.
>> Imagine a set of objects identified by some piece of information, such as a
> "key" slot (guaranteed to be constant for any particular element).  The
> object could look like this:
>> class Element(object):
>    def __init__(self, key):
>        self.key = key
>    def __eq__(self, other):
>        return self.key == other
>    def __hash__(self):
>        return hash(self.key)
>    # ...
>> Now imagine a set "s" of such objects.  I can add them to the set:
>>>>> s = set()
>>>> s.add(Element('foo'))
>>>> s.add(Element('bar'))
>> I can test membership using the keys:
>>>>> 'foo' in s
> True
>>>> 'blah' in s
> False
>> But I can't seem to find a way to retrieve the element corresponding to
> 'foo', at least not without iterating over the entire set.  Is this an
> oversight or an intentional feature?  Or am I just missing an obvious way to
> do this?

My instinct is that it's intentional. I'd say that you're abusing
__eq__ here. If you can say "x in s" and then can't use x as if it
were the actual item inserted into s, then are they really "equal"?
Using a dict seems like the correct answer. I certainly don't think
it's worth complicating the set interface to cover this corner case.
Paul.


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /