[Python-ideas] An identity dict

spir ☣ denis.spir at gmail.com
Sun May 30 13:20:47 CEST 2010


On Sun, 30 May 2010 03:27:53 +0000 (UTC)
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 is how Lua works, systematically. To make this work, all "primitive" values (non-table, since table is the single container type) are interned. Thus, for "values", equality and identity are equivalent. Tables instead are considered referenced objects, even when they are used as collections.
So that Lua can quietly hash the ref instead of the value.
* simplicity
* performance
* anything can be used as key

The drawback is that any structured value, eg an x,y position stored in a table, is compared by reference. A lookup with a position used as key thus cannot return an item stored with an equal key:
> p1 = {x=1,y=2}
> p2 = {x=1,y=2}
> t = {[p1]="abc"}
> print(t[p1],tp2)
abc	nil
Conversely, collections which, conceptually, are referenced things, do not erroneaously return false positive because of value comparison. (The case does not happen in python since collections cannot be used as keys).

For the scheme to really extend to any use case, there should be a kind of mark allowing the programmer to state whether a table is, conceptually, a value (simply happens to be structured) or a referenced thing. Value tables should then be interned like other values -- but this is certainly difficult and costly.


Denis
________________________________

vit esse estrany ☣

spir.wikidot.com



More information about the Python-ideas mailing list