Python callable() Function



The Python callable() function is a built-in function that is used to determine whether the object passed as an argument can be called. An object is said to be callable if it implements the __call__() method. Here, the passed object could be functions, methods, variables and classes.

If the specified object is callable, this function returns True otherwise, False. Remember, although the callable() function may return TRUE, it's not necessary that the object will always be callable. There could be cases where it fails. However, if the return value is FALSE, then it is certain that the object is not callable.

Syntax

The syntax of the Python callable() function is as follows −

callable(object)

Parameters

The Python callable() function accepts a single parameter −

  • object − It represents an object such as a list, string, function etc.

Return Value

The Python callable() function returns a Boolean value.

Examples

Now, let's understand the working of callable() function with the help of some examples −

Example 1

The following example shows the basic use of Python callable() function. Here we are creating a user-defined function and applying callable() function to check whether the given function is callable.

def checkerFun():
    return "This is Tutorialspoint"

output = callable(checkerFun)
print("Is the given method is callable:", output) 

When we run above program, it produces following result −

Is the given method is callable: True

Example 2

In the code below, we have a lambda expression and the callable() function checks if this expression can be called or not. Since this lambda expression is callable, this method will return True.

lambdaExp = lambda x: x * 3
output = callable(lambdaExp)
print("Is the given lambda expression is callable:", output)

Following is an output of the above code −

Is the given lambda expression is callable: True

Example 3

The code below shows the use of callable() function with a given class and its instance. Since the class and instance are callable, this method will return True for both cases.

class NewClass:
   def __call__(self):
      print("Tutorialspoint")

print("Is the class is callable:")
print(callable(NewClass))  

instanceOfClass = NewClass()
print("Is the instance is callable:")
print(callable(instanceOfClass)) 

Output of the above code is as follows −

Is the class is callable:
True
Is the instance is callable:
True

Example 4

In the code below a string is created. Then, with the help of callable() function, we check if the passed string is callable or not.

nonCallableStr = "I am not callable String"
output = callable(nonCallableStr)
print("Is the string is callable:", output)

Following is an output of the above code −

Is the string is callable: False
python_built_in_functions.htm
Advertisements