[Python-ideas] An identity dict

Mike Graham mikegraham at gmail.com
Sun May 30 19:04:39 CEST 2010


What is the use case for such a collection? (This will help answer
questions about how stuff like comparing two identity dicts or an
identity dict and another mapping will work.)

By default, objects __eq__ and __hash__ methods allow them to be used
in dicts by identity. When I define __eq__ to mean something else, I
find that I don't typically have something I can really store in a
dict with the behavior I want.

Should an ID Dict really be a weak ref identity dict? The one time I
wanted an ID dict is when I was writing a memoization routine for
methods, where I wanted to store the caches for each object.
(Incidentally, I ended up refactoring not to require this anyhow.) Is
this the main basic use case? Am I missing something?

Best regards,
Mike


On Sat, May 29, 2010 at 10:27 PM, Benjamin Peterson <benjamin at python.org> wrote:
> In the spirit of collections.OrderedDict and collections.defaultdict, I'd like
> to propose collections.identitydict. It would function just like a normal
> dictionary, but ignore hash values and comparison operators and merely lookup
> keys based on the key's id().
>
> This dict is very useful for keep track of objects that should not be compared
> by normal comparison methods. For example, I would use an identitydict to hold
> weak references that would otherwise fallback to their referant object's hash.
>
> An advantage of formalizing this in collections would be to enable other Python
> implementations like PyPy, where id() is expensive, to provide an optimized
> identitydict.
>
> Regards,
> Benjamin



More information about the Python-ideas mailing list