Which standard python exception, if any, should be used in the case where a value is missing for the proper execution of a function ? TypeError
and ValueError
seemed good candidates to me but according to the documentation (my italics) :
Passing arguments of the wrong type (e.g. passing a
list
when anint
is expected) should result in aTypeError
, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in aValueError
.ValueError : Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
Neither of these descriptions seem to me to quite capture the idea of a missing value. But none of the other exceptions in the standard seem to come even close either.
Here's an example. Objects of type myclass
can be instantiated in two different ways, each of which requires a specific parameter. If neither of them is provided, the init fails.
class myclass(object):
def __init__(self,firstparam=None,secondparam=None):
if firstparam:
self.firstinit()
elif secondparam:
self.secondinit()
else:
#What to put here ?
raise Exception("Missing value for myclass")
if __name__=="__main__":
#oops, forgot to specify a parameter here !
myobj=myclass()
Of course, I know I can always implement my own MissingValueError
exceptions subclasses when writing a library. I am asking this question in order not to duplicate something that might already exist in the standard.
The proper exception would be TypeError
:
>>> def a(b,c) : print b,c
...
>>> a(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a() takes exactly 2 arguments (1 given)
>>>
And as a side note, I'd recommend NOT to provide the default values to the required arguments, so the user of your class will clearly understand (s)he has to provide some.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With