Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the standard exception for a missing value in python?

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 an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.

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.

like image 382
Typhon Avatar asked Dec 16 '19 01:12

Typhon


1 Answers

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.

like image 167
lenik Avatar answered Sep 22 '22 12:09

lenik