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 42 >>> from collections import Callable >>> for item in lst: ... if isinstance((item,Callable): print( item() ) 42 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. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor