summaryrefslogtreecommitdiffstats
path: root/Lib/collections.py
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-12-15 16:30:37 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-12-15 16:30:37 (GMT)
commit96f3410ebeaf970d7f214d1be1527d8e7c1cc03b (patch)
tree329232dc4455df1d39c026d649f95a49fd17361f /Lib/collections.py
parent779f19e7a7116da0a683498260077eec1a40257a (diff)
downloadcpython-96f3410ebeaf970d7f214d1be1527d8e7c1cc03b.zip
cpython-96f3410ebeaf970d7f214d1be1527d8e7c1cc03b.tar.gz
cpython-96f3410ebeaf970d7f214d1be1527d8e7c1cc03b.tar.bz2
Issue 10667: Fast path for collections.Counter
Diffstat (limited to 'Lib/collections.py')
-rw-r--r--Lib/collections.py15
1 files changed, 12 insertions, 3 deletions
diff --git a/Lib/collections.py b/Lib/collections.py
index f05d7b4..061106b 100644
--- a/Lib/collections.py
+++ b/Lib/collections.py
@@ -334,6 +334,17 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
### Counter
########################################################################
+def _count_elements(mapping, iterable):
+ 'Tally elements from the iterable.'
+ mapping_get = mapping.get
+ for elem in iterable:
+ mapping[elem] = mapping_get(elem, 0) + 1
+
+try: # Load C helper function if available
+ from _collections import _count_elements
+except ImportError:
+ pass
+
class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
@@ -476,9 +487,7 @@ class Counter(dict):
else:
dict.update(self, iterable) # fast path when counter is empty
else:
- self_get = self.get
- for elem in iterable:
- self[elem] = 1 + self_get(elem, 0)
+ _count_elements(self, iterable)
if kwds:
self.update(kwds)