Created
May 23, 2012 01:15
-
-
Save inlinestyle/2772697 to your computer and use it in GitHub Desktop.
An extension of collections.defaultdict that I wish were in the stdlib.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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