I am using Sphinx to document one of my projects and one of the classes takes in a function as a parameter in its __init__
. Is there a standard way to document this function-type parameter? I am also using sphinx.ext.napoleon
to use Google formatting for my docstrings.
Here's an example:
class ExampleClass:
"""An example class to demonstrate my question
Args:
func (what goes here?): Description of the parameter
"""
def __init__(self, func):
self.func = func
def do_something(self, param):
"""An example method
Args:
param (str): Description of param
Returns:
bool: The return description
"""
return self.func(param)
In my code, the parameter in question should take in one str
and return a bool
. Is there a standard way to document this when using Sphinx?
The simplest way to document the function parameter is using
typing.Callable
. By doing so the static type checker will verify that the signature (arguments and return type) of the passed function is compatible with the type hint.However, this has one potential problem. If you look at the Python Data Model, in the sub-section titled "Callable types" under 3.2 The standard type hierarchy. You'll notice there are several possible types that are callables, and any callable with the specified signature would not cause a warning from the static type checker. For example, a class instance implementing the
__call__()
method would not cause a warning:You can type hint the
param
signature as shown above together with validating thatparam
is of typeFunctionType
in the__init__
as you would validate other parameters at run-time, and raise aTypeError
exception if the parameter is not a function.It may be possible to combine both requirements
Callable[[str], bool]
andFunctionType
as an intersection using structural subtyping, I have not yet tried that approach.Finally some examples are included that would cause the static type checker to raise warnings: