You might have heard about callables in Python. Before exploring them, I considered only functions as callables. But we shall soon find out how wrong I was. So let's dive in.
callable
?Anything that can be called using parenthesis '()' (possibly by passing arguments) is a callable
. So the following objects are callable:
All the above objects are callable because they have __call__
attribute defined inside them. Let's see if this is correct.
>>> # Function
>>> def test():
... pass
...
>>> hasattr(test, '__call__')
True
>>>
>>> # Class
>>> class SimpleClass:
... # Method
... def func(self):
... pass
...
>>> hasattr(SimpleClass, '__call__')
True
>>> hasattr(SimpleClass.func, '__call__')
True
>>>
>>>
>>> simple_obj = SimpleClass()
>>> hasattr(simple_obj, '__call__')
False
>>> simple_obj()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'SimpleClass' object is not callable
Above, we defined a function and a class with a method. Then we use the hasattr
built-in function to check if they have the __call__
attribute. Finally, we see that an instance of the class does not have the call attribute and hence it is not callable.
However, we can make an instance of a class callable by defining call method inside the class. Let's add call attribute to our SimpleClass
and see whether this is correct.
>>> class SimpleClass:
... def func(self):
... pass
... def __call__(self):
... print('I am callable now')
...
>>> simple_obj = SimpleClass()
>>> simple_obj()
I am callable now
It turns out that our claim is correct. We defined call method inside the SimpleClass and magically the instance of the class 'simple_obj' is now callable. Likewise, we can make an instance of any class callable by defining the call method.
A better way to check if an object is callable is using the built-in callable function like so:
>>> callable(test)
True
>>> callable(SimpleClass)
True
>>> callable(SimpleClass.func)
True
>>> callable(simple_obj)
True
>>> callable(4)
False
>>>
In the above code, we use the callable
function on different objects and check whether they are callable or not.
In this post, we explored and found out the following:
An object in Python is callable
if it has a __call__
attribute.
Following are callables in Python:
Instances of a class can be made callable. To check if an object is callable, we could use the following built-in functions:
Leave a comment