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

Steven D'Aprano steve at pearwood.info
Sun May 22 09:31:52 EDT 2016

On Sun, May 22, 2016 at 10:15:16AM +0000, Stefan Krah wrote:
> Steven D'Aprano <steve at ...> writes:
> > So I propose that InvalidOperation be changed to inherit from
> > ValueError, to match the expected behaviour from other numeric types.
> One problem is that often a *combination* of values triggers InvalidOperation.
> ValueError does not really fit here.

I don't see why it matters whether it is one value or a combination of 
values, it's still a value error.

>  In this scenario other modules use
> TypeError, but I'm not a fan of that use either:
> >>> Decimal("inf") * Decimal(0)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

I'm not sure what you mean by this example, and what it has to do with 
TypeError. The error shown is related to the *value* of the arguments, 
namely Decimal inf and Decimal zero, not their types. Both arguments are 

> >>> Decimal("inf") * Decimal("inf")
> Decimal('Infinity')

Again, I don't see the relevance of this example. Multiplying Decimal 
infinity by another Decimal infinity is well-defined, and not an error.

> Additionally, InvalidOperation is part of Decimal's custom exception handling
> via the context, so it would be a bit odd if ValueError were part of that.

Perhaps I am mistaken, but none of Decimal's custom exception handling 
would need to change. That's the beauty of multiple inheritence. If we 
add ValueError as a base class, InvalidOperation is a subclass of both 
DecimalException and ValueError. The custom exception handling will 
continue to work the same way it does now, and people who expect 
Decimal("spam") to raise ValueError will also be satisfied.


More information about the Python-ideas mailing list