Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 493
NotAnAmbiTurner Avatar asked Aug 13 '26 05:08

NotAnAmbiTurner


1 Answers

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.

like image 133
Martijn Pieters Avatar answered Aug 15 '26 14:08

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!