PROGRAMMING IN PYTHON
In programming languages, callable objects are often associated with functions, and for good reason. Functions are perhaps the best examples of callable objects, but they are not the only ones. In Python, there are many other callable types, which can be incredibly useful and powerful. You can also create your own callable objects. This article is about both.
a callable is an object that can be called using a pair of parentheses, like below where we use the built-in function sum()
:
>>> sum((1, 1, 1))
3
A call to a callable, depending on its definition, can be
- without any argument, as in
no_args_callable()
- or a series of positional and/or keyword arguments, as in
args_callable(arg1, arg2)
,args_callable(arg1, arg2=value2)
eitherargs_callable(arg1=value1, arg2=value2)
Above, I described a callable as a noun. The word callableHowever, it is also used as an adjective, i.e. being a summonable. Therefore, a callable object is the same as a callable object.
Python has a built-in function, callable()
, which checks whether an object is callable or, in other words, whether it is callable. Consider the following examples of actual callables:
>>> callable(lambda x: x + 1)
True
>>> callable(print)
True
>>> def foo(): ...
>>> callable(foo)
True
The following objects are not callable:
>>> callable(None)
False
>>> callable(10)
False
>>> callable("hello")
False
The positive examples above were referring to functions, which is what most people associate with callables. However, in fact, all Python classes can be called. If you know the basics of object-oriented programming in Python, you know that to create an instance of a class, you need to do the following:¹
>>> class Empty: ...
This looks exactly like a call, and it is, and that’s why Python classes are callable.
This code shows that the Empty
The class is callable, but the truth is that all Python classes are callable. However, in Python…