Python callable

Summary: in this tutorial, you’ll learn about Python callable objects and how to use the callable function to check if an object is callable.

Introduction to Python callables

When you can call an object using the () operator, that object is callable:

object()Code language: Python (python)

For example, functions and methods are callable. In Python, many other objects are also callable.

A callable always returns a value.

To check if an object is callable, you can use the built-in function callable:

callable(object)Code language: Python (python)

The callable function accepts an object. It returns True if the object is callable. Otherwise, it returns False.

Python callable function examples

The following illustrates the various types of callable objects in Python.

1) built-in functions

All built-in functions are callable. For example, print, len, even callable.

print(callable(print))
print(callable(len))
print(callable(callable))Code language: Python (python)

Output:

True
True
True
Code language: PHP (php)

2) User-defined functions

All user-defined functions created using def or lambda expressions are callable. For example:

def add(a, b):
    return a + b


print(callable(add))  # True
print(callable(lambda x: x*x))  # TrueCode language: Python (python)

Output:

True 
TrueCode language: PHP (php)

3) built-in methods

The built-in method such as a_str.upper, a_list.append are callable. For example:

str = 'Python Callable'
print(callable(str.upper))  # TrueCode language: Python (python)

Output:

TrueCode language: PHP (php)

4) Classes

All classes are callable. When you call a class, you get a new instance of the class. For example:

class Counter:
    def __init__(self, start=1):
        self.count = start

    def increase(self):
        self.count += 1

    def value(self):
        return self.countCode language: Python (python)

5) Methods

Methods are functions bound to an object, therefore, they’re also callable. For example:

print(callable(Counter.increase))  # TrueCode language: Python (python)

Output:

TrueCode language: PHP (php)

6) Instances of a class

If a class implements the __call__ method, all instances of the class are callable:

class Counter:
    def __init__(self, start=1):
        self.count = start

    def increase(self):
        self.count += 1

    def value(self):
        return self.count

    def __call__(self):
        self.increase()


    counter = Counter()
    counter()

    print(callable(counter))  # TrueCode language: Python (python)

Output:

TrueCode language: PHP (php)

Summary

  • An object is callable when it can be called using the () operator.
  • Use the Python callable built-in function to check if an object is callable or not.
Did you find this tutorial helpful ?