[Python-ideas] statistics module in Python3.4

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Fri Jan 31 11:12:15 CET 2014


Chris Angelico <rosuav at ...> writes:

> 
> On Fri, Jan 31, 2014 at 12:07 PM, Steven D'Aprano <steve at ...> wrote:
> > One of my aims is to avoid raising TypeError unnecessarily. The
> > statistics module is aimed at casual users who may not understand, or
> > care about, the subtleties of numeric coercions, they just want to take
> > the average of two values regardless of what sort of number they are.
> > But having said that, I realise that mixed-type arithmetic is difficult,
> > and I've avoided documenting the fact that the module will work on mixed
> > types.
> 
> Based on the current docs and common sense, I would expect that
> Fraction and Decimal should normally be there exclusively, and that
> the only type coercions would be int->float->complex (because it makes
> natural sense to write a list of "floats" as [1.4, 2, 3.7], but it
> doesn't make sense to write a list of Fractions as [Fraction(1,2),
> 7.8, Fraction(12,35)]). Any mishandling of Fraction or Decimal with
> the other three types can be answered with "Well, you should be using
> the same type everywhere". 

Well, that's simple to stick to as long as you are dealing with explicitly
typed input data sets, but what about things like:

a = transform_a_series_of_data_somehow(data)
b = transform_this_series_differently(data)

statistics.mean(a+b) # assuming a and b are lists of transformed values

potentially different types are far more difficult to spot here and the fact
that the result of the above might not be the same as, e.g.,:

statistics.mean(b+a)

is not making things easier to debug.


>(Though it might be useful to allow
> int->anything coercion, since that one's easy and safe.)
> 

It should be mentioned here that complex numbers are not currently dealt
with by statistics._sum .

>>> statistics._sum((complex(1),))
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    s._sum((complex(1),))
  File ".\statistics.py", line 158, in _sum
    n, d = exact_ratio(x)
  File ".\statistics.py", line 257, in _exact_ratio
    raise TypeError(msg.format(type(x).__name__)) from None
TypeError: can't convert type 'complex' to numerator/denominator

Best,
Wolfgang



More information about the Python-ideas mailing list