]> granicus.if.org Git - python/commitdiff
Fix minor subclassing issue with collections.Counter
authorRaymond Hettinger <python@rcn.com>
Fri, 15 Apr 2011 20:21:30 +0000 (13:21 -0700)
committerRaymond Hettinger <python@rcn.com>
Fri, 15 Apr 2011 20:21:30 +0000 (13:21 -0700)
1  2 
Lib/collections.py
Lib/test/test_collections.py
Misc/NEWS

index 98c432575344e66900f9624a406f81280adc0559,30301ce89f64252735b3b4bc0e5e871d9bc49fe4..c77b08972cada08221a6c5e3ae5b9b30a4fa1f98
@@@ -508,36 -458,9 +508,36 @@@ class Counter(dict)
          if kwds:
              self.update(kwds)
  
 +    def subtract(self, iterable=None, **kwds):
 +        '''Like dict.update() but subtracts counts instead of replacing them.
 +        Counts can be reduced below zero.  Both the inputs and outputs are
 +        allowed to contain zero and negative counts.
 +
 +        Source can be an iterable, a dictionary, or another Counter instance.
 +
 +        >>> c = Counter('which')
 +        >>> c.subtract('witch')             # subtract elements from another iterable
 +        >>> c.subtract(Counter('watch'))    # subtract elements from another counter
 +        >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
 +        0
 +        >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
 +        -1
 +
 +        '''
 +        if iterable is not None:
 +            self_get = self.get
 +            if isinstance(iterable, Mapping):
 +                for elem, count in iterable.items():
 +                    self[elem] = self_get(elem, 0) - count
 +            else:
 +                for elem in iterable:
 +                    self[elem] = self_get(elem, 0) - 1
 +        if kwds:
 +            self.subtract(kwds)
 +
      def copy(self):
-         'Like dict.copy() but returns a Counter instance instead of a dict.'
-         return Counter(self)
+         'Return a shallow copy.'
+         return self.__class__(self)
  
      def __reduce__(self):
          return self.__class__, (dict(self),)
Simple merge
diff --cc Misc/NEWS
Simple merge