3

I am looking for the equivalent of PHPs InvalidArgumentException to use in case a function gets an argument that has an incorrect type. I'm working with Python 3. (And I am quite new to Python.)

ValueError documentation states "argument that has the right type but an inappropriate value", so is not the right one to use here.

TypeError documentation states "Raised when an operation or function is applied to an object of inappropriate type", and thus also does not seem applicable.

What is the correct error type to use in my case?

2
  • Why do you think TypeError is no good?
    – doctorlove
    Sep 20, 2013 at 15:30
  • What sort of functions are you writing that need type checking?
    – doctorlove
    Sep 20, 2013 at 15:34

3 Answers 3

7

I would go with TypeError in your case.

A function is applied to an object of inappropriate type can be understood as passing an argument of the wrong type (the function is applied to its arguments).

For instance, len(42) raises TypeError, because len() cannot be applied to a number.

2
2
int([])
#>>> Traceback (most recent call last):
#>>>   File "<string>", line 88, in <module>
#>>>   File "", line 1, in <module>
#>>> TypeError: int() argument must be a string or a number, not 'list'

Is that not the sort of error you're looking for?

Note that type-checking is ill-advised since it'll throw errors anyway if it doesn't support the wanted interface and not checking allows duck-typing.

1
  • 2
    I understand that in the Python community, duck-typing is generally accepted and type checking frowned upon. I generally dislike duck-typing, as it is not good for error locality, and is less strict. That is however personal preference, both approaches have their merits. Sep 20, 2013 at 15:42
0

Here is a quick way to check if the type is not matching or matches:

def my_function(my_word: str):
    if type(my_word) != str:
        raise Exception("Whatever exception you want to raise!")
    pass

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.