On Sun, May 30, 2010 at 6:34 AM, Antoine Pitrou
<solipsis@pitrou.net> wrote:
Perhaps it would be more useful to add a generic
collections.keyfuncdict, taking a function which applied to a key
gives the real key value used for lookups.
Your identity dict would be created as:
d = collections.keyfuncdict(id)
For what it's worth, my sorteddict class (part of the blist library) already supports exactly that syntax. The full signature is:
sorteddict([key[, arg]], **kw)
where "arg" and "kw" do exactly what they do for dict(), and "key" specifies a key function just as in your example. (Although now that I think about it, perhaps "arg" and "key" should be reversed to more closely match the signature of dict())
Example usage:
>>> from blist import sorteddict
>>> d = sorteddict(id)
>>> d[(1,2)] = True
>>> d[(1,2)] = True
>>> d.keys()
[(1, 2), (1, 2)]
I'm not suggesting that Benjamin use sorteddict for his use-case, since keeping the keys sorted by id() is probably not useful. ;-)
In some ways it would be nice if dict() itself accepted a "key" function as an argument, but I don't see a way to provide that functionality without adding another field to PyDictObject (yuck) or abusing the ma_lookup field (again, yuck).
I favor adding the more general keyfuncdict over identitydict.