Sobes.tech
Junior
201

What is a callable object in Python?

Answer from AI

sobes.tech AI

In Python, a callable object is any object that can be called like a function. This means that the call operator () can be applied to it.

Callables include:

  • Functions: Defined using the def keyword.
  • Methods: Functions associated with an object (class instance).
  • Classes: Calling a class creates a new instance of that class.
  • Objects with a __call__ method: If a class defines a __call__ method, its instances become callable.
# Function
def my_function():
    pass

# Method
class MyClass:
    def my_method(self):
        pass

# Class
class AnotherClass:
    pass

# Object with __call__
class CallableObject:
    def __call__(self, *args, **kwargs):
        pass

# Check if callable
import collections.abc

print(isinstance(my_function, collections.abc.Callable))
print(isinstance(MyClass().my_method, collections.abc.Callable))
print(isinstance(AnotherClass, collections.abc.Callable))
print(isinstance(CallableObject(), collections.abc.Callable))

You can also use the built-in function callable() to check if an object is callable.

# Check with callable()
print(callable(my_function))
print(callable(MyClass().my_method))
print(callable(AnotherClass))
print(callable(CallableObject()))
print(callable(123)) # Not a callable object

Callable objects are widely used in Python to implement various patterns such as decorators, callbacks, and functional programming.