Python callable() and __call__()

Filed Under: Python

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.


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:


Person Class is callable =  True
Person object is callable =  False

python callable, python __call__

Python callable() and __call__() example

Let’s define a class with __call__() function.


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:


<__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.


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:


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.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation callable, Official Documentation call

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages