[Tutor] collections.Callable functionality

Peter Otten __peter__ at web.de
Mon Mar 6 03:31:53 EST 2017


ramakrishna reddy wrote:

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

That's a pretty exotic beast that you stumbled upon.

>>> from collections.abc import Callable

You can use it to check if an object is callable, i. e. works like a 
function:

>>> isinstance("foo", Callable)
False
>>> isinstance(str, Callable)
True
>>> isinstance(lambda: 42, Callable)
True

You can also use it as a baseclass if you want to prevent subclasses from 
being instantiated unless they implement a __call__() method which makes 
those instances callable:

>>> class C(Callable): pass
... 
>>> c = C()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class C with abstract methods __call__
>>> class D(C):
...     def __call__(self, name="Al"):
...         return "You can call me {}".format(name)
... 
>>> d = D()
>>> isinstance(d, Callable)
True
>>> d()
'You can call me Al'




More information about the Tutor mailing list