SHARE
TWEET

defauldict.py

rodrigoclira Jun 13th, 2014 554 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2.  
  3. class defaultdict(dict):
  4.     def __init__(self, default_factory=None, *a, **kw):
  5.         if (default_factory is not None and
  6.             not hasattr(default_factory, '__call__')):
  7.             raise TypeError('first argument must be callable')
  8.         dict.__init__(self, *a, **kw)
  9.         self.default_factory = default_factory
  10.     def __getitem__(self, key):
  11.         try:
  12.             return dict.__getitem__(self, key)
  13.         except KeyError:
  14.             return self.__missing__(key)
  15.     def __missing__(self, key):
  16.         if self.default_factory is None:
  17.             raise KeyError(key)
  18.         self[key] = value = self.default_factory()
  19.         return value
  20.     def __reduce__(self):
  21.         if self.default_factory is None:
  22.             args = tuple()
  23.         else:
  24.             args = self.default_factory,
  25.         return type(self), args, None, None, self.items()
  26.     def copy(self):
  27.         return self.__copy__()
  28.     def __copy__(self):
  29.         return type(self)(self.default_factory, self)
  30.     def __deepcopy__(self, memo):
  31.         import copy
  32.         return type(self)(self.default_factory,
  33.                           copy.deepcopy(self.items()))
  34.     def __repr__(self):
  35.         return 'defaultdict(%s, %s)' % (self.default_factory,
  36.                                         dict.__repr__(self))
  37.  
  38. def recursively_default_dict():
  39.     return defaultdict(recursively_default_dict)
  40.  
  41.  
  42. if __name__ == '__main__':
  43.     dic = recursively_default_dict()
  44.     dic['a']['b']['c'] = 3
  45.     dic['a']['b']['d'] = 4
  46.  
  47.     print "dic['a']['b']['d']", dic['a']['b']['c']
  48.     print "dic['a']['b']['d']", dic['a']['b']['d']
RAW Paste Data
Top