2009/4/3 Hrvoje Niksic <hrvoje.nik...@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. _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com