On Fri, Sep 03, 2021 at 05:31:33PM -0700, Guido van Rossum wrote:
> I know you don't. My point with that example was to show how unlikely it is
> that someone would write that in the first place (since the code would
> always fail rather than in specific cases).
I have code that does something similar, as feature-detection. I want to
be able to call gcd with any number of items, but older versions don't
support that.
from math import gcd
try:
gcd()
except TypeError:
# support arbitrary arguments
def gcd(*args):
# implementation goes here
In this specific case, I can safely catch TypeError, because with no
arguments at all, what else could it be? But a ParameterError exception
would express my intent better. And other function calls may not be so
easily distinguished.
Here's another example:
try:
it = zip(a, b, strict=True)
except TypeError:
...
I can get away with catching TypeError because zip doesn't immediately
iterate over the arguments. But that may not always be the case:
from some_library import interleave
# interleave([1,2,3], [4,5,6]) --> [1, 4, 2, 5, 3, 6]
try:
list_of_pairs = interleave(a, b, strict=True)
except TypeError:
# meaning what?
In this hypothetical example, it would be good to distinguish between
*wrong type* TypeErrors, and *wrong parameter* TypeErrors.
> I find it unlikely that TypeError (in particular) is of much use for
> repairing a situation, precisely because it is raised for situations where
> a value has an incorrect type.
But not *only* for those situations. It is also used for situations
where the number of arguments, or the keyword names, are wrong. And that
can be fixed by retrying the call, possibly by calling a slower
alternative.
This may not seem appealing to you if you mostly or exclusively write
code targetting a single version of Python, but if your code has to work
with multiple versions, or if you are using third-party libraries where
the API of functions may change, then I think it is useful to be able to
distinguish parameter errors (wrong number of arguments, or wrong
keywords) from the case where the arguments have the wrong type.
I've often done this, and *mostly* I've been lucky enough that I could
come up with a call where the TypeError could only mean something like
"invalid keyword argument". But it would be useful to be able to express
that more directly.
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/3OIGABULEOORHKYIHC3OQJXNVB4AKYQV/
Code of Conduct: http://python.org/psf/codeofconduct/