0

I want python to raise an exception if the argument type does not match the parameter type. Function example:

def add_integers (a: int, b:int) -> int:
    return a + b

What that function will return with different arguments

add_integers(1,2) = 3
add_integers(True,2) = 3
add_integers("1",2) = Exception (because it cannot add str and int)

I want to make sure that the function does not except an argument of type boolean and ONLY integers. I know I can make an if statement to check the type and raise an exception myself or maybe use a decorator function , but I was wondering if there is a simpler way of doing it?

4
  • What is wrong with the TypeError which is raised? Commented Jul 9, 2022 at 8:46
  • It is not raised for booleans in this case, python will handle True as 1, but I want it to give me a TypeError Commented Jul 9, 2022 at 8:48
  • My opinion is that you will be better off having a unit test check these things. What advantage do you get with an exception at runtime? Commented Jul 9, 2022 at 8:52
  • 1
    If you want python to work more like a statically typed language, you should check out mypy. Without mypy type hints only serve as code documentation. Commented Jul 9, 2022 at 9:42

1 Answer 1

1

You can use the built-in function type . This returns the class of the object and does not consider sub-classes. Which is an issue with isinstance as it will also return true if you check if a boolean is an int

>>> type(1) is int
True
>>> type(True) is int
False
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.