Python callable(object) function returns True
if the object appears callable, otherwise it returns False
.
Python callable and __call__()
Python object is called callable if they define __call__()
function. If this function is defined then x(arg1, arg2, …) is a shorthand for x.__call__(arg1, arg2, …).
Note that callable() function returns True if the object appears callable, it’s possible that it returns True even if the object is not callable. However, if this function returns False then the object is definitely not callable.
Also, a python class is always Callable. So always use callable() with an instance of the class, not the class itself. Let’s look at a simple example to check this behavior.
1 2 3 4 5 6 7 8 9 |
class Person: i = 0 def __init__(self, id): self.i = id p = Person(10) print('Person Class is callable=", callable(Person)) print("Person object is callable=", callable(p)) |
Output:
1 2 3 4 5 |
Person Class is callable = True Person object is callable = False <img class="alignnone wp-image-22662 size-full" src="http://all-learning.com/wp-content/uploads/2018/08/Python-callable-and-__call__.png" alt="Python callable and __call__()" width="1200" height="628" /> |
Python callable() and __call__() example
Let’s define a class with __call__() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Employee: id = 0 name = "" def __init__(self, i, n): self.id = i self.name = n def __call__(self, *args, **kwargs): print('printing args') print(*args) print('printing kwargs') for key, value in kwargs.items(): print("%s == %s" % (key, value)) e = Employee(10, 'Pankaj') # creating object print(e) # printing object print(callable(e)) |
*args
is used to allow passing variable arguments to the __call__() function.
**kwargs
is used to allow passing named arguments to the __call__() function.
Output:
1 2 3 4 |
<__main__.Employee object at 0x107e9e1d0> True |
Let’s look at some code snippets where we will use callable() to check if the object is callable, then call the instance as a function.
1 2 3 4 5 6 7 8 |
if callable(e): e() # object called as a function, no arguments e(10, 20) # only args e.__call__(10, 20) e(10, 20, {'x': 1, 'y': 2}) # only args of different types e(10, 'A', name="Pankaj", id=20) # args and kwargs both |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
printing args printing kwargs printing args 10 20 printing kwargs printing args 10 20 printing kwargs printing args 10 20 {'x': 1, 'y': 2} printing kwargs printing args 10 A printing kwargs name == Pankaj id == 20 |
That’s all for Python callable() and __call__() functions.
Reference: Official Documentation callable, Official Documentation call