The philosophy of how to use different objects in a Python program is called duck typing—if it looks like a duck, quacks like duck, and walks like a duck, it's a duck. Objects are grouped not by what their type is but what they are capable of doing, and this even extends to functions. When writing a Python program, you should always know what all your objects can do and use them without checking.
For example, I could define a function
def add_three(a, b c):
return a + b + c
and mean for it to be used with three floats. But by not checking this, I have a much more useful function—I can use it with ints, with decimal.Decimals, or with fractions.Fractions, for example.
The same applies to having a function. If I know I have a function and want to call it, I should just call it. Maybe what I have is a function and maybe I have a different callable (like a bound method or an instance of an arbitrary class that defines __call__
) that could be just as good. By not checking anything, I make my code able to handle a wide range of circumstances I might not even have thought of in advance.
In the case of callables, I can pretty reliably determine whether I have one or not, but for the sake of my code's simplicity, I shouldn't want to. If someone passes in something that's not callable, you'll get an error when you call it anyways. If I'm writing code that accepts a parameter that may be a callable or not and I do different things depending on it, it sounds like I should improve my API by defining two functions to do these two different things.
If you did have a way to handle the case where the caller passed in something that isn't function-like (and this wasn't just the result of an insane API), the right solution would be to catch the TypeError
that is raised when you try to call something that can't be called. In general, it's better to try to do something and recover if it fails rather than to check ahead of time. (Recall the cliché, "It's easier to ask forgiveness than permission.") Checking ahead of time can lead to unexpected problems based on subtle errors in logic and can lead to race conditions.
Why do you think you need to typecheck?