diff --git a/kombu/common.py b/kombu/common.py index 270be5f5..d2b2ba08 100644 --- a/kombu/common.py +++ b/kombu/common.py @@ -8,10 +8,10 @@ Common Utilities. :license: BSD, see LICENSE for more details. """ -from collections import defaultdict from kombu import entity from kombu.utils import uuid +from kombu.utils.compat import defaultdict declared_entities = defaultdict(lambda: set()) diff --git a/kombu/utils/compat.py b/kombu/utils/compat.py index 176faafb..9db5057d 100644 --- a/kombu/utils/compat.py +++ b/kombu/utils/compat.py @@ -274,3 +274,51 @@ class LifoQueue(Queue): def _get(self): return self.queue.pop() + +############## collections.defaultdict ###################################### + +try: + from collections import defaultdict +except ImportError: + # Written by Jason Kirtland, taken from Python Cookbook: + # + class defaultdict(dict): + + def __init__(self, default_factory=None, *args, **kwargs): + dict.__init__(self, *args, **kwargs) + self.default_factory = default_factory + + def __getitem__(self, key): + try: + return dict.__getitem__(self, key) + except KeyError: + return self.__missing__(key) + + def __missing__(self, key): + if self.default_factory is None: + raise KeyError(key) + self[key] = value = self.default_factory() + return value + + def __reduce__(self): + f = self.default_factory + args = f is None and tuple() or f + return type(self), args, None, None, self.iteritems() + + def copy(self): + return self.__copy__() + + def __copy__(self): + return type(self)(self.default_factory, self) + + def __deepcopy__(self): + import copy + return type(self)(self.default_factory, + copy.deepcopy(self.items())) + + def __repr__(self): + return "defaultdict(%s, %s)" % (self.default_factory, + dict.__repr__(self)) + import collections + collections.defaultdict = defaultdict # Pickle needs this. +