Python callable() and __call__() with Examples

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.

Output:

Python callable() and __call__() example

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

*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:

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.

Output:

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

By admin

Leave a Reply

%d bloggers like this: