Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a "callable" parameter in a Python docstring?

Consider an implementation of filterNot (basically the opposite of filter):

def filterNot(f, sequence):
    return filter(lambda x: not f(x), sequence)

The parameter f can be a "function" or a "method" or a lambda -- or even an object whose class defines __call__.

Now consider a line of docstring for this parameter:

:param ??? f: Should return True for each element to be abandoned

Now, what should go in place of ??? -- how should the type of parameter f be referred to in a docstring. callable is the obvious choice (and what I would dictate if I were calling the shots :P) but is there an established convention?

like image 435
Chris W. Avatar asked May 09 '14 18:05

Chris W.


1 Answers

Yes, the term callable is the one to use here.

The abstract base class Callable exists in collections.abc - abstract base classes can be best thought of as interfaces (although more like they dynamic ones in Go than those in Java, for example) - they define an interface, and any class that has the given functions is defined as inheriting from that abstract base class (whether they did so explicitly or not) - this means anything you would usefully pass into a function like this would be a subclass of Callable, making the use of the term completely correct here. Just as you might say Iterable.

It is definitely the term used by most people in when talking informally about Python code, and anyone reading your code should understand what you mean.

The callable() built-in (that got removed for a while in 3.x, then added back) does the check for function-like objects, and this further reinforces the name as the best choice where you are looking for function-like objects.

like image 140
Gareth Latty Avatar answered Sep 24 '22 01:09

Gareth Latty