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

Stefan Krah stefan at bytereef.org
Sun May 22 06:15:16 EDT 2016


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. 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'>]

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


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.



> py> decimal.Decimal([])
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: argument must be a sequence of length 3

That is a ValueError because in principle list and tuple types are
accepted due to the somewhat arcane from_tuple() conversion:

>>> Decimal([0, [], 'F'])
Decimal('Infinity')


Since this is a Python specific extension, ValueError looks appropriate
here.

Count me -1 on any changes here.


Stefan Krah






More information about the Python-ideas mailing list