heckman
heckman

Reputation: 46

How to get a useful exception message from decimal in python 3?

With Python 2, creating a Decimal with an invalid string produces a useful error message:

>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 547, in __new__
    "Invalid literal for Decimal: %r" % value)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3872, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: 'spam'

While Python 3 produces a not-so-helpful message:

>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

Is there any way to get a useful message like "Invalid literal for Decimal: 'spam'" from the exception in Python 3?

I'm using Python 2.7.15 and Python 3.7.2, both on darwin.

Addenda:

It looks like Python 2 once had a not-very-helpful message for decimal.InvalidOperation: https://bugs.python.org/issue1770009

This situation looks analogous but most of it goes over my head: https://bugs.python.org/issue21227

Upvotes: 0

Views: 1396

Answers (1)

JBirdVegas
JBirdVegas

Reputation: 11403

You could monkey-patch the decimal module.

import decimal


def safe_decimal(something):
    try:
        funct_holder(something)
    except Exception as e:
        new_errror = Exception("Hey silly that's not a decimal, what should I do with this? {}".format(something))
        raise new_errror from None


funct_holder = decimal.Decimal
decimal.Decimal = safe_decimal

Then you could use the monkey patched version as so

>>> decimal.Decimal('hello')
Traceback (most recent call last):
  File "<input>", line 12, in <module>
  File "<input>", line 6, in safe_decimal
Exception: Hey silly that's not a decimal, what should I do with this? hello

Upvotes: 1

Related Questions