[Python-ideas] Should decimal.InvalidOperation subclass ValueError?

Chris Angelico rosuav at gmail.com
Sun May 22 05:01:30 EDT 2016


On Sun, May 22, 2016 at 6:45 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Looking at the docs, there are nine examples given of things which can
> raise InvalidOperation (if not trapped, in which case they return a
> NAN):
>
> Infinity - Infinity
> 0 * Infinity
> Infinity / Infinity
> x % 0
> Infinity % x
> sqrt(-x) and x > 0
> 0 ** 0
> x ** (non-integer)
> x ** Infinity
>
> plus invalid string conversion. To my mind, ValueError would be an
> acceptable error for all of these things.

Hmm. Out of interest, I probed fractions.Fraction for comparable
behaviours. AFAIK, there's no way to represent infinity as a Fraction;
using a floating-point infinity just converts the Fraction to a float
and continues as per float; and mixing Fraction and Decimal either
instantly raises TypeError, or (in the case of x**infinity) converts
to float and *then* raises TypeError. 0 ** 0 simply returns 1. I can't
get a ValueError out of any of the given operations.

Why is x ** (non-integer) an InvalidOperation? Is that specifically
for a negative value for x? The example you quoted [1] isn't clear
there. (I also don't know why it describes the square root example
that way, and not as "sqrt(x) and x < 0", but presumably there's a
good mathematical reason for that.)

> So I propose that InvalidOperation be changed to inherit from
> ValueError, to match the expected behaviour from other numeric types.

+1.

ChrisA
[1] https://docs.python.org/3/library/decimal.html#decimal.InvalidOperation


More information about the Python-ideas mailing list