【问题标题】:Is there a standard format for documenting function-type parameters in Sphinx using sphinx.ext.napoleon?是否有使用 sphinx.ext.napoleon 在 Sphinx 中记录函数类型参数的标准格式?
【发布时间】:2020-07-26 17:37:36
【问题描述】:

我正在使用 Sphinx 来记录我的一个项目,其中一个类在其 __init__ 中接收一个函数作为参数。是否有标准方法来记录此函数类型参数?我还使用 sphinx.ext.napoleon 为我的文档字符串使用 Google 格式。

这是一个例子:

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 时是否有标准方法来记录这一点?

【问题讨论】:

标签: python python-sphinx type-hinting docstring sphinx-napoleon


【解决方案1】:

记录函数参数的最简单方法是使用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

但是,这有一个潜在的问题。如果您查看sub-section titled "Callable types" under 3.2 The standard type hierarchy 中的 Python 数据模型。您会注意到有几种可能的类型是可调用的,并且任何具有指定签名的可调用都不会导致来自静态类型检查器的警告。 例如,实现__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 签名,如上所示,并在__init__ 中验证param 的类型为FunctionType,就像在运行时验证其他参数一样,并引发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 这两个要求结合为an intersection using structural subtyping,我还没有尝试过这种方法。

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

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

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多