[Tutor] collections.Callable functionality

Alan Gauld alan.gauld at yahoo.co.uk
Mon Mar 6 03:20:52 EST 2017

On 06/03/17 03:07, ramakrishna reddy wrote:

> Can you please explain the functionality of collections.Callable ? If
> possible with a code snippet.

First of all, do you understand the concept of callable in Python?
Any object that can be used like a function is callable.
You might have a mixed container of callable and non-callable objects
and want to determine at runtime which are which:

>>> def f(): return 42   # f is callable
>>> lst = [2,'three',f]  # only f is callable
>>> for item in lst:
...    if callable(item): print( item() )  # call it
>>> from collections import Callable
>>> for item in lst:
...    if isinstance((item,Callable): print( item() )

So you can use Callable with isinstance as an alternate
to the callable() builtin test. I can't actually think
of a situation where I would want to do that but it
could arise.

Callable is an abstract class that requires an
implementation of the method __call__. You can use it
as a superclass of your own callable classes.

Frankly I'm not sure it's really very useful since
you can make your own classes callable by simply
adding a __call__ method. And indeed doing so
makes your class appear to be an instance of
Callable. Somebody obviously thought there was a
need for it and persuaded the community. There
will be a PEP somewhere you could read. It is 3119...

It says among other things:
This PEP proposes a particular strategy for organizing these tests known
as Abstract Base Classes, or ABC. ABCs are simply Python classes that
are added into an object's inheritance tree to signal certain features
of that object to an external inspector. Tests are done using
isinstance() , and the presence of a particular ABC means that the test
has passed.
So I suspect Callable is simply included for consistency with
the other test types.

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list