Both approaches are useful, but what if you want stricter control during runtime? You can take it a step further with isinstance()
checks to validate parameter types explicitly.
Here’s how:
def add_numbers(a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Both parameters must be integers")
return a + b
This ensures that the parameters are integers before proceeding. It’s especially helpful when you want to prevent misuse early in execution, particularly in larger or more complex systems where incorrect types might cause downstream issues.