Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #39656 > unrolled thread

Re: Question about defaultdict

Started byPeter Otten <__peter__@web.de>
First post2013-02-23 11:34 +0100
Last post2013-02-23 11:34 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Question about defaultdict Peter Otten <__peter__@web.de> - 2013-02-23 11:34 +0100

#39656 — Re: Question about defaultdict

FromPeter Otten <__peter__@web.de>
Date2013-02-23 11:34 +0100
SubjectRe: Question about defaultdict
Message-ID<mailman.2335.1361615640.2939.python-list@python.org>
Frank Millman wrote:

> I use a dictionary as a cache, and I thought that I could replace it
> with collections.defaultdict, but it does not work the way I expected
> (python 3.3.0).
> 
> my_cache = {}
> def get_object(obj_id):
>      if obj_id not in my_cache:
>          my_object = fetch_object(obj_id)  # expensive operation
>          my_cache[obj_id] = my_object
>      return my_cache[obj_id]
> my_obj = get_object('a')
> 
> I thought I could replace this with -
> 
> from collections import defaultdict
> my_cache = defaultdict(fetch_object)
> my_obj = my_cache['a']
> 
> It does not work, because fetch_object() is called without any arguments.
> 
> It is not a problem, but it would be neat if I could get it to work. Am
> I missing anything?

You can subclass the ordinary dict:

class Cache(dict):
    def __missing__(self, key):
        result = self[key] = fetch_object(key)
        return result

_cache = Cache()
def get_object(object_id):
    return _cache[object_id]

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web