【问题标题】:Documenting different argument possibilities on same function记录同一函数的不同参数可能性
【发布时间】:2017-06-16 02:18:07
【问题描述】:

我正在使用带有 sphinx.ext.autodoc 的 Google 样式的文档字符串来自动为我的函数生成文档,并确保它们在代码中正确地自我记录。

我有一个函数def myfunc(id=None, size=None, hash=None),它根据idsize + hash返回信息。如果我们有id 作为参数,则不需要sizehash,如果我们有sizehash 作为参数,则不需要id

使用 sphinx,可以指定一个可选参数,但在这种情况下,我们不知道什么是强制性的,什么是可选的。这是一个例子:

def get_file(id=0, size=0, hash="")
    """
    Get file metadata.

    Args:
        id (int): id of the file.
        size (int): file size in bytes.
        hash (str): md5 hash of file.

    Returns:
        file_data (str): metadata information about the file.
    """
    if id:
        # Get file with id.
        ...
    elif size and hash:
        # Get file with size and hash.
        ...
    else:
        # Bad arguments, handle error.
        ...

    return file_data

问题是:如何判断文档字符串中需要哪些参数?

您很容易争辩说函数本身就是问题所在,即使结果相同,两个参数对也应该位于不同的函数中:

def get_file_by_id(id)
    """
    Get file metadata from id.

    Args:
        id (int): id of the file.

    Returns:
        file_data (str): metadata information about the file.
    """

    # Get file with id.
    ...

    return file_data

def get_file_by_hash(size, hash)
    """
    Get file metadata from hash.

    Args:
        size (int): file size in bytes.
        hash (str): md5 hash of file.

    Returns:
        file_data (str): metadata information about the file.
    """

    # Get file with hash+size.
    ...

    return file_data

但在这种情况下,如果可能,最好使用单个函数,因为该函数是与另一个使用单个函数的 API 的绑定。

【问题讨论】:

    标签: python python-sphinx docstring sphinx-napoleon


    【解决方案1】:

    根据文档here,以下示例方法定义:

    def module_level_function(param1, param2=None, *args, **kwargs):
    

    文档字符串定义为:

    Args:
        param1 (int): The first parameter.
        param2 (:obj:`str`, optional): The second parameter. Defaults to None.
            Second line of description should be indented.
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.
    

    因此,您明确说明了什么是可选,否则将被理解为强制参数。

    【讨论】:

    • 这告诉参数是否是可选的,但如果我的情况适用于这个例子,如果使用 param2param1 将变为可选。
    • 它的用法有点难以理解。如果您正在设计一个采用可选参数的函数,那么可以理解它正是 that。如果这对参数需要一起给出,您可能希望将它们放在一个命名元组或其他一些有用的结构中。这可能是更好的设计选择。
    • 就个人而言,我认为为了清晰和明确起见,您应该坚持拆分功能。此外,使文档更易于编写。
    • 一个元组(size, hash) 可以简化问题,但我们仍然需要一个函数来接受id (size, hash)。我同意用法很复杂,我愿意接受任何替代方案。
    • 我不确定这个与 API 的绑定是如何设置的。但是,您可以做的是让您的 API 与之通信的单一方法,并在该方法中查看您收到的有效负载。从该有效负载中,您可以看到提供了哪些参数。根据提供的内容,您调用适当的方法。否则你会因为不符合合同要求而提出。
    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 2022-01-13
    • 2016-04-18
    • 2020-01-23
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    相关资源
    最近更新 更多