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

Nick Coghlan ncoghlan at gmail.com
Sun May 22 11:14:36 EDT 2016

On 23 May 2016 at 00:35, Stefan Krah <stefan at bytereef.org> wrote:
> Steven D'Aprano <steve at ...> writes:
> [snipping excessively, since gmane.org started to lecture on this.]
>> 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.
> They won't be if they do setcontext(ExtendedContext).

At that point they've explicitly asked for unknown strings to be
converted to "NaN", and the behaviour won't be changed by Steven's

However, while I can see Steven's point (folks expect to be able to
catch malformed strings with ValueError), I don't believe the
InvalidOperation would be the right place to adjust the hierarchy, as
in terms of base classes, the decimal exceptions already inherit from
ArithmeticError, which is the common base class of ZeroDivisionError,
OverflowError, and FloatingPointError (which I would consider the
closest analogy to decimal.InvalidOperation for binary floating point
values), and those have the same behaviour of bypassing except clauses
that catch ValueError:

>>> def to_float(arg):
...     try:
...         return float(arg)
...     except ValueError:
...         return float("nan")
>>> to_float(10*100)
>>> to_float("spam")
>>> to_float(10**10000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_float
OverflowError: int too large to convert to float

To address *just* the case of string conversion, it would suffice to
introduce a dedicated decimal.ParsingError exception inheriting from
both InvalidOperation and ValueError, specifically for failures
converting from a string to a decimal value.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list