[issue20481] Clarify type coercion rules in statistics module

Oscar Benjamin report at bugs.python.org
Mon Feb 3 12:11:46 CET 2014


Oscar Benjamin added the comment:

It's not as simple as registering with an ABC. You also need to provide the
interface that the ABC represents:

>>> import sympy
>>> r = sympy.Rational(1, 2)
>>> r
1/2
>>> r.numerator
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Half' object has no attribute 'numerator'

AFAIK there are no plans by any third part libraries to increase their
inter-operability with the numeric tower.

My point is that in choosing what types to accept and how to coerce them you
should focus on actual practical benefits rather than theoretical ones. If it
can be done in a way that means it works for more numeric types then that's
great. But when I say "works" I mean that it should ideally achieve the best
possible accuracy for each type.

If that's not possible then it might be simplest to just document how it works
for combinations of the std lib types (and perhaps subclasses thereof) and
then say that it will fall back on coercing to float for anything else. This
approach is simpler to document and for end-users to understand. It also has
the benefit that it will work for all non std lib types (that I'm aware of)
without pretending to achieve more accuracy than it can.

>>> import sympy, fractions, gmpy
>>> fractions.Fraction(sympy.Rational(1, 2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/fractions.py", line 148, in __new__
    raise TypeError("argument should be a string "
TypeError: argument should be a string or a Rational instance
>>> float(sympy.Rational(1, 2))
0.5
>>> fractions.Fraction(gmpy.mpq(1, 2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/fractions.py", line 148, in __new__
    raise TypeError("argument should be a string "
TypeError: argument should be a string or a Rational instance
>>> float(gmpy.mpq(1, 2))
0.5

Coercion to float via __float__ is well supported in the Python ecosystem.
Consistent support for getting exact integer ratios is (unfortunately) not.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue20481>
_______________________________________


More information about the Python-bugs-list mailing list