Search code examples
pythonexceptionraise

Is there a built-in Python Exception for validation of function input?


I have a function which expects a tuple as one of the arguments

def func(x,
         t # t should be a tuple of a predefined type (str, bool, str)
         ):
    ...

Is there a built-in error which is appropriate for saying that t is not of the correct type, or should I be defining my own?


Solution

  • Yes, the TypeError exception is meant to be used for exactly this case:

    Raised when an operation or function is applied to an object of inappropriate type.

    [...]

    Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError[.]

    You may want to look into using type hinting, to catch programmers errors that pass in the wrong type early. We check type hints during linting time, for example.