Question about defaultdict

F

Frank Millman

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,049
Members
48,769
Latest member
Clifft

Latest Threads

Top