[Python-checkins] cpython: Issue #20478: avoid special casing Counter in statistics

nick.coghlan python-checkins at python.org
Sat Feb 8 10:44:49 CET 2014


http://hg.python.org/cpython/rev/78d0b7472697
changeset:   89029:78d0b7472697
user:        Nick Coghlan <ncoghlan at gmail.com>
date:        Sat Feb 08 19:44:16 2014 +1000
summary:
  Issue #20478: avoid special casing Counter in statistics

Passing Counter objects to the Counter constructor is
special cased, going through iter() firsts ensures they
are handled the same way as any other iterable.

(Committing on Steven's behalf as I don't believe his
SSH key is registered yet)

files:
  Lib/statistics.py           |  4 +---
  Lib/test/test_statistics.py |  8 ++++++++
  Misc/NEWS                   |  3 +++
  3 files changed, 12 insertions(+), 3 deletions(-)


diff --git a/Lib/statistics.py b/Lib/statistics.py
--- a/Lib/statistics.py
+++ b/Lib/statistics.py
@@ -268,9 +268,7 @@
 
 def _counts(data):
     # Generate a table of sorted (value, frequency) pairs.
-    if data is None:
-        raise TypeError('None is not iterable')
-    table = collections.Counter(data).most_common()
+    table = collections.Counter(iter(data)).most_common()
     if not table:
         return table
     # Extract the values with the highest frequency.
diff --git a/Lib/test/test_statistics.py b/Lib/test/test_statistics.py
--- a/Lib/test/test_statistics.py
+++ b/Lib/test/test_statistics.py
@@ -1355,6 +1355,14 @@
         # collections.Counter, which accepts None and returns an empty dict.
         self.assertRaises(TypeError, self.func, None)
 
+    def test_counter_data(self):
+        # Test that a Counter is treated like any other iterable.
+        data = collections.Counter([1, 1, 1, 2])
+        # Since the keys of the counter are treated as data points, not the
+        # counts, this should raise.
+        self.assertRaises(statistics.StatisticsError, self.func, data)
+
+
 
 # === Tests for variances and standard deviations ===
 
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -24,6 +24,9 @@
 Library
 -------
 
+- Issue #20478: the statistics module now treats collections.Counter inputs
+  like any other iterable.
+
 - Issue #17369: get_filename was raising an exception if the filename
   parameter's RFC2231 encoding was broken in certain ways.  This was
   a regression relative to python2.

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list