首页 > 解决方案 > 是否有使用 sphinx.ext.napoleon 在 Sphinx 中记录函数类型参数的标准格式?

问题描述

我正在使用 Sphinx 来记录我的一个项目,其中一个类在其__init__. 是否有标准方法来记录此函数类型参数?我也sphinx.ext.napoleon习惯于对我的文档字符串使用谷歌格式。

这是一个例子:

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)

在我的代码中,有问题的参数应该接受一个str并返回一个bool. 使用 Sphinx 时是否有标准方法来记录这一点?

标签: pythonpython-sphinxtype-hintingdocstringsphinx-napoleon

解决方案


记录函数参数的最简单方法是使用typing.Callable. 通过这样做,静态类型检查器将验证传递函数的签名(参数和返回类型)是否与类型提示兼容。

from typing import Callable

class ExampleClassTwo:
    """An example class to demonstrate my question.

    Args:
        func (Callable[[str], bool]): Description of the parameter.
    """
    def __init__(self, func: Callable[[str], bool]):

        self.func = func

然而,这有一个潜在的问题。如果您查看 Python 数据模型,在3.2 标准类型层次结构下标题为“可调用类型”的小节中。您会注意到有几种可能的类型是可调用的,任何具有指定签名的可调用都不会导致来自静态类型检查器的警告。例如,实现该__call__()方法的类实例不会引起警告:

def str_function(param: str) -> bool:
    pass

class OneInstance:

    def __init__(self, param):
        pass

    def __call__(self, param: str) -> bool:
        pass

one_instance = OneInstance("test instance")
# neither of the below raise a static type check warning
one = ExampleClassTwo(str_function)
two = ExampleClassTwo(one_instance)

您可以键入提示param签名,如上所示,同时验证param类型为FunctionType in,就像在运行时验证其他参数一样,如果参数不是函数__init__ ,则引发异常。TypeError

from typing import Callable
from types import FunctionType

class ExampleClassTwo:
    """An example class to demonstrate my question

    Args:
        func (Callable[[str], bool]): Description of the parameter
    Raises:
        TypeError: Argument `param` is not of type ``FunctionType``.
    """

    def __init__(self, func: Callable[[str], bool]):

        if type(func) in (FunctionType,):
            self.func = func
        else:
            raise TypeError("param must be initialized as being of ``FunctionType``.")

可以将这两个需求结合起来,Callable[[str], bool]FunctionType作为一个使用结构子类型的交集,我还没有尝试过这种方法。

最后包含一些示例,这些示例会导致静态类型检查器发出警告:

def int_function(param: int) -> bool:
    pass


class ExampleClass:
    """An example class to demonstrate my question

    Args:
        func (FunctionType): Description of the parameter
    """

    def __init__(self, func: FunctionType):
        self.func = func

three = ExampleClass(str_function("test string"))  # Expected type 'FunctionType', got 'bool' instead
four = ExampleClass(str_function)  # Expected type 'FunctionType', got '(param: str) -> bool' instead
five = ExampleClass(type(str_function))  # No warning five.func is {type} <class 'function'>

six = ExampleClassTwo(int_function(2))  # Expected type '(str) -> bool', got 'bool' instead
seven = ExampleClassTwo(str_function("test string"))  # Expected type '(str) -> bool', got 'bool' instead
eight = ExampleClassTwo(int_function)  # Expected type '(str) -> bool', got '(param: int) -> bool' instead
nine = ExampleClassTwo(str_function)  # No warning

在此处输入图像描述


推荐阅读