Skip to content

Instantly share code, notes, and snippets.

@inlinestyle
Created May 23, 2012 01:15
Show Gist options
  • Save inlinestyle/2772697 to your computer and use it in GitHub Desktop.
Save inlinestyle/2772697 to your computer and use it in GitHub Desktop.
An extension of collections.defaultdict that I wish were in the stdlib.
import inspect
from types import FunctionType
from collections import defaultdict
class FactoryDict(defaultdict):
"""
>>> fd = FactoryDict(int)
>>> fd['foo'] += 7
>>> fd['foo']
7
>>>
>>> fd = FactoryDict(lambda x: x**2)
>>> fd[3] += 7
>>> fd[3]
16
"""
def __init__(self, default_factory):
defaultdict.__init__(self, default_factory)
self.factory_takes_args = isinstance(default_factory, FunctionType) and any(inspect.getargspec(default_factory))
def __missing__(self, item):
val = self.default_factory(item) if self.factory_takes_args else self.default_factory()
self[item] = val
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment