简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM