Add support for unary plus and unary minus to collections.Counter()
diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py
index 03bd2b3..2007e68 100644
--- a/Lib/collections/__init__.py
+++ b/Lib/collections/__init__.py
@@ -672,6 +672,17 @@
result[elem] = newcount
return result
+ def __pos__(self):
+ 'Adds an empty counter, effectively stripping negative and zero counts'
+ return self + Counter()
+
+ def __neg__(self):
+ '''Subtracts from an empty counter. Strips positive and zero counts,
+ and flips the sign on negative counts.
+
+ '''
+ return Counter() - self
+
########################################################################
### ChainMap (helper for configparser and string.Template)
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index eb6d4d7..04c4d97 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -943,6 +943,11 @@
c.subtract('aaaabbcce')
self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))
+ def test_unary(self):
+ c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
+ self.assertEqual(dict(+c), dict(c=5, d=10, e=15, g=40))
+ self.assertEqual(dict(-c), dict(a=5))
+
def test_helper_function(self):
# two paths, one for real dicts and one for other mappings
elems = list('abracadabra')