[Python-ideas] keyfuncdict -- the good, the bad, and the ugly

Jim Jewett jimjjewett at gmail.com
Wed Jun 2 21:31:47 CEST 2010


On Wed, Jun 2, 2010 at 2:25 PM, Raymond Hettinger
<raymond.hettinger at gmail.com> wrote:
> Was thinking of all the things that could be done with Antoine's generalization:

> The Good
> ========
> d = keyfuncdict(key=str.lower)        # case insensitive dict

Will the keyfunc be an immutable attribute?  If so, this satisfies
some of the security proxy use cases too.  (Those might also want to
be able to transform the value -- perhaps on the way out.  But
allowing access to key, value, item, and in/out ... I'm not sure
exactly where to draw YAGNI.)


> The Bad
> =======

> d = keyfuncdict(key=tuple)                    # lets you use lists as keys

Obviously, this would be for a limited domain, to avoid tupling
numbers.  But given that ... why is this bad?

Is it just because this might be an attractive nuisance for people who
really ought to be using key=id?  (Same question for key in (repr,
pickle.loads))

> d = keyfuncdict(key=getuser)               # track one most recent entry per user

Assuming a reasonble getuser, what is wrong with this?


> The Ugly
> ========

> d = keyfuncdict(key=random.random)           # just plain weird

This reminds me of the gremlins testing tools, though I admit that I
can't quite come up with a good use.

> d = keyfuncdict(key=itertools.count().next)   # all entries are unique and unretrievable ;-)

But you could still iterate over them, in creation order.  The
advantage over a list is unclear.

> def remove(obj):
>     d.pop(obj)
>     return obj
> d = keyfuncdict(key=remove)                          # self deleting dict ;-)

Again, probably most useful for testing ... is it actually harmful to
allow this?

-jJ



More information about the Python-ideas mailing list