Get item from set

Raymond Hettinger python at
Wed Apr 29 15:55:54 CEST 2009

[bearophileH... at]
> But some other times you may accept to change the class and the set/
> dict, making it tell apart the keys only when they are different
> object:
> class Some(object):
>     def __init__(self, y):
>         self._y = y
>     def __eq__(self, other):
>         return self is other
>     def __hash__(self):
>         return hash(self._y)
> Now your set/dict keeps all the instances, even when they contain the
> same _y.

David Mertz suggested something like this in one of his Developer
articles.  Essentially, he was describing an IdentityDict or

I don't really see how those would be useful in regular python.
Why treat equal but not identical objects as distinct in an
environment where you have so little control over object identity?

>>> s = IdentitySet(['abc'])
>>> e = 'ab' + 'c'   # distinct element, equal to 'abc', but not identical
>>> e in s

For the most part, we can't even count on equal integers having the
same identity:

>>> x = 1000
>>> y = 1001 - 1
>>> [id(o) for o in (x, y)]
[16675616, 16676240]

I'm curious about your use cases for the Some() class in conjunction
with a dict or set.


More information about the Python-list mailing list