]> granicus.if.org Git - python/commitdiff
Issue #20478: avoid special casing Counter in statistics
authorNick Coghlan <ncoghlan@gmail.com>
Sat, 8 Feb 2014 09:44:16 +0000 (19:44 +1000)
committerNick Coghlan <ncoghlan@gmail.com>
Sat, 8 Feb 2014 09:44:16 +0000 (19:44 +1000)
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)

Lib/statistics.py
Lib/test/test_statistics.py
Misc/NEWS

index a67a6d11cd6c058c6e9e47b28af0447829f05cbd..9359ed71e51497c5b20e0125e0b4d35c4594af56 100644 (file)
@@ -268,9 +268,7 @@ def _coerce_types(T1, T2):
 
 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.
index 3d30d88f697ecd5149498a45c995c79231ecbfb4..6db821fc6e305376a34770037a9431a3ab195650 100644 (file)
@@ -1355,6 +1355,14 @@ class TestMode(NumericTestCase, AverageMixin, UnivariateTypeMixin):
         # 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 ===
 
index 58938e0e01cbc66c5770bdacc0af0e7a9a702207..9f8f43c7cbc89acb97dcb57e9e1bc15dfb4c375b 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -24,6 +24,9 @@ Core and Builtins
 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.