Python Simplified

PythonSimplifiedcomLogo

What is a callable in Python?

Python Callables resized

Introduction

Let’s start the discussion with a simple function that prints “Python Simplified” as you can see below. How do you call this function hello? By using the function name followed by parenthesis i.e. hello(). Right? 

If you just use hello without parenthesis it just prints the type of the object (i.e. function). So, in order to call the function, you will have to use the ( ) operator.

				
					def hello():
    print("Python Simplified")

hello
>>> <function __main__.hello()>

hello()
>>> "Python Simplified"
				
			

This means that all functions can be called. But what if you want to check programmatically if the given object can be called or not. Python provides a built-in function callable() for this task.

Difference between functions and methods

Let’s understand the difference between functions and methods as we’ll be referring to both in this article. So it’s important that you understand the difference between the two.

  • Both function and method definition looks exactly the same and performs almost the same. The main difference is that methods are related to classes and objects.
  • Functions exist independently and can be called only by their name. But on the other hand, methods don’t exist independently. In order to use the method, you need to create an object of the class first and then invoke the method on the object. 
				
					# Example 1 
def hello():  # This is a function
    print("Python Simplified")

hello()
				
			
				
					"Python Simplified"
				
			
				
					# Example 2
class say_hello:
    def hello(self):   # This is a method
        print("Python Simplified")

hello_obj = say_hello()
hello_obj.hello()
				
			
				
					"Python Simplified"
				
			

What is a callable

Anything (or any object) that can be called using ( ) operator is called a callable. By reading the introduction and based on the above definition, I assume you must be thinking that functions and methods are callable in Python. You are right! But partly! Because not only functions and methods, there are other objects that are callable. 

Using Python’s built-in function callable() you can check if the given object is callable or not. The syntax for callable is shown below. As you can see it can take one positional-only argument.

				
					callable(obj, /)
				
			

The callable function returns: 

True — if the passed object appears to be callable.

False — if the passed object is not callable.

When callable() returns True

1. Functions

a) Built-in functions

As the name itself says built-in functions are also functions hence they are callable too i.e. callable() returns True. As seen from the below example, all the built-in functions are callables.

				
					callable(min)
callable(max)
callable(print)
callable(int)
callable(float)
				
			
				
					True
True
True
True
True
				
			

b) User-defined functions

Similar to built-in functions, all user-defined functions are also callable i.e. callable() returns True. In the below example, hello() is a user-defined function is  a callable.

				
					def hello(user):
    print(f"Welcome to Python Simplified, {user}")

callable(hello)
				
			
				
					True
				
			

c) Lambda functions

Lambda functions are no exceptions. Since lambdas are also function and they are also callable as well. Refer to the example below and lambda is returns True with callable().

				
					callable(lambda x: x**2)
				
			
				
					True
				
			

2. User-defined classes

The user-defined classes are also callable. It is evident from the below code that the user-defined class Rectangle is callable.

				
					class Rectangle:
    def __init__(self, width, height):
        self.height = height
        self.width = width
    def area(self):
        return self.width * self.area

callable(Rectange)
				
			
				
					True
				
			

3. Methods

a) Built-in methods

Everything is an object in Python. The objects are created from their respective classes and these classes contain methods. For example, the list class contains built-in methods such as insert, pop, remove, etc. Similarly, int, float, range, etc have their own methods. All these built-in methods are also callable

In the below list example, you can see that append and remove are callables as callable() returns True.

				
					my_list = [1,2,3,4,5]
callable(my_list.append)
callable(my_list.remove)
				
			
				
					True
True
				
			

Refer to another example using str (string) class. String class has many built-in methods we often use such as upper, lower, startswith, endswith, replace, etc. All these built-in methods are callable too.

				
					my_string = "python simplified"
callable(my_string.upper)
callable(my_string.startswith)
callable(my_string.endswith)
callable(my_string.replace)
				
			
				
					True
True
True
True
				
			

b) User-defined methods

The instance methods are also callable. In the below example, we created an object r1 of class Rectangle. And r1’s method area is callable.

				
					r1 = Rectangle(10, 20)
callable(r1.area)
				
			
				
					True
				
			

c) staticmethods and classmethods

Static methods & class methods are the methods that can be called without creating an object of a class. How these two methods work is beyond the scope of this article. But don’t worry. We’ll cover this topic in future blog posts. The sample code confirms that both my_func2 (class method) and my_func3 (static method) are callable.

				
					class MyClass:
    def my_func1(self):
        print("Inside the instance method")
    
    @classmethod
    def my_func2(cls):
        print("Inside the class method")
    
    @staticmethod
    def my_func3():
        print("Inside the static method")

callable(MyClass.my_func2)
callable(MyClass.my_func3)
				
			
				
					True
True
				
			

4. Class instances (objects)

By default class instances i.e. objects are not callable. In order to make class instances callable, you need to implement the special method __call__ in the class definition.

The below example returns False because class instances are not callable.

				
					r2 = Rectangle(10, 20)
callable(r2)
				
			
				
					False
				
			

After adding the __call__() method, class instance r3 is now callable as you can see from the code below. And, if you call r3(), it will return the area of the rectangle as per our code.

				
					class Rectangle:
    def __init__(self, width, height):
        self.height = height
        self.width = width
        
    def __call__(self):
        return self.width * self.height

r3 = Rectangle(10, 20)
callable(r3)
				
			
				
					True
				
			

5. Decorator

A decorator allows a user to add new functionality to an existing object without modifying its structure. As you can see from the example below, my_decorator is a callable object. 

				
					def my_decorator(func):
    def wrapper():
        print("I am inside the decorator")
        func()
    return wrapper

@my_decorator
def hello():
    print("Hello")

callable(my_decorator)
				
			
				
					True
				
			

When to use the callable() function

You won’t be using the callable() built-in function often in your daily work. But here are a couple of real-world use-cases:

  • One use case where callable function comes useful is with libraries that generate automated documentation. Because to generate automated documentation they have to scan through the code base and understand the structure (classes, functions, which objects are callable, etc.). For example, The pydoc module automatically generates documentation from Python modules and if you look at the source code of pydoc, it uses the callable() function to achieve its task.
  • The callable() function is used extensively in the Standard Python libraries. For example, if you look at the source code of the libraries such as asyncio, email, encodings, functools, inspect, etc you will notice that callable() is being used in these built-in modules.

Conclusion

In this article, we talked about Python’s built-in function callable(), its definition, the syntax, and the examples when a callable function returns True or False. You also understood the real-world use case of the callable() function. Hope you found this article useful. If you have any questions, please do let me know in the comments.

References

Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on email
Chetan Ambi

Chetan Ambi

A Software Engineer & Team Lead with over 10+ years of IT experience, a Technical Blogger with a passion for cutting edge technology. Currently working in the field of Python, Machine Learning & Data Science. Chetan Ambi holds a Bachelor of Engineering Degree in Computer Science.
Scroll to Top