[Python-ideas] Should decimal.InvalidOperation subclass ValueError?
Nick Coghlan
ncoghlan at gmail.com
Sun May 22 22:56:40 EDT 2016
On 23 May 2016 at 08:34, Greg Ewing <greg.ewing at canterbury.ac.nz> 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.
>
>
> Related to this, is there any good reason that ArithmeticError
> doesn't derive from ValueError?
>
> If it did, it would fix this issue with Decimal and possibly
> others as well.
>
> I ran into this a while ago with a function like
>
> def convert(x, t):
> try:
> return t(x)
> except ValueError:
> ...
>
> and found that not all numeric types raise something derived from
> ValueError from their constructors.
I considered suggesting that, but got stuck on the question of how we
quantify the compatibility implications - such a shift would change
the behaviour of code that catches both, but handles them differently.
That is, this code would be fine:
try:
...
except (ArithmeticError, ValueError):
...
As would this:
try:
...
except ArithmeticError:
...
except ValueError:
...
But this would change to executing the first except clause rather than
the second if the inheritance hierarchy changed:
try:
...
except ValueError:
...
except ArithmeticError:
...
While I can honestly say I've never seen an except clause catching
ArithmeticError directly in the wild, I see more of a risk in the fact
we'd potentially be silently changing the way ZeroDivisionError and
OverflowError are handled.
That said, this feels like the *right* answer to me, it's just the
compatibility risk that worries me.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list