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


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

Question about defaultdict

Started byFrank Millman <frank@chagford.com>
First post2013-02-23 12:13 +0200
Last post2013-02-23 12:13 +0200
Articles 1 — 1 participant

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


Contents

  Question about defaultdict Frank Millman <frank@chagford.com> - 2013-02-23 12:13 +0200

#39653 — Question about defaultdict

FromFrank Millman <frank@chagford.com>
Date2013-02-23 12:13 +0200
SubjectQuestion about defaultdict
Message-ID<mailman.2332.1361614398.2939.python-list@python.org>
Hi all

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?

Frank Millman

[toc] | [standalone]


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


csiph-web