keyfuncdict -- the good, the bad, and the ugly
Was thinking of all the things that could be done with Antoine's generalization: The Good ======== d = keyfuncdict(key=str.lower) # case insensitive dict def track(obj): logging.info(obj) return obj d = keyfuncdict(key=track) # monitored dict d = keyfuncdict(key=id) # makes benjamin happy The Bad ======= d = keyfuncdict(key=tuple) # lets you use lists as keys d = keyfuncdict(key=repr) # support many kinds of mutable or unhashable keys d = keyfuncdict(key=pickle.loads) # use anything picklable as a key d = keyfuncdict(key=getuser) # track one most recent entry per user The Ugly ======== d = keyfuncdict(key=random.random) # just plain weird d = keyfuncdict(key=itertools.count().next) # all entries are unique and unretrievable ;-) def remove(obj): d.pop(obj) return obj d = keyfuncdict(key=remove) # self deleting dict ;-) Raymond
On Wed, Jun 2, 2010 at 2:25 PM, Raymond Hettinger <raymond.hettinger@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
participants (2)
-
Jim Jewett
-
Raymond Hettinger