[Tutor] Python 3: string to decimal conversion
Steven D'Aprano
steve at pearwood.info
Sun May 22 04:16:33 EDT 2016
On Sat, May 21, 2016 at 01:34:20PM -0500, Saidov wrote:
> "decimal.InvalidOperation was unhandled by user code
> Message: [<class 'decimal.ConversionSyntax'>]"
>
> *Question: *I tried looking up the meaning of this error, but couldn't find
> anything on the internet. *Can someone help me understand what's wrong with
> my code?*
https://duckduckgo.com/html/?q=decimal+InvalidOperation+python
will take you to the docs for Python 2. Changing the URL to version 3
gives us:
https://docs.python.org/3/library/decimal.html
and searching for InvalidOperation gives us:
https://docs.python.org/3/library/decimal.html#decimal.InvalidOperation
which is not a lot of help as it only lists *some* of the things which
will lead to that error, but we can try it at the interactive
interpreter:
py> import decimal
py> decimal.Decimal("25")
Decimal('25')
py> decimal.Decimal("25x")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
So the problem here is that when you call Decimal() with an invalid
argument, you are expecting a ValueError, but Python raises
decimal.InvalidOperation instead:
> try:
> expenses[ts.Date(row[0]).month] += decimal.Decimal(row[4])
> except ValueError:
> pass
--
Steve
More information about the Tutor
mailing list