如何在 Python 中为 returns None 但将文件写入磁盘的函数编写文档字符串?

How to write docstring in Python for a function that returns None but write files in disk?

我想使用 Python 文档字符串来更好地记录我的代码。

在下面的函数中,它将一个列表作为输入并将一个文件写入磁盘。我想知道如何在 docstring 中记录函数的输出作为函数 return 在 None 中键入。它有约定吗?

def foo(list_of_items: list) -> None :
    """Simple function.

    Parameters
    ----------
        list_of_items : list of str
        list of some texts    

    Returns
    -------
        what is the best way to write this section?
    """

    file = open('/path/output.txt')
    file.write(list_of_items[1])
    file.close()

关于类型提示的唯一 Python 约定是:

Non-goals, PEP 484

It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.

考虑到这一点,有 . Two syntaxes have their own style guide, see numpydoc docstring guide and Google Python Style Guide - 3.8 Comments and Docstrings. (By comparison PEP 8 and PEP 257 不那么具体)。

只有 return None 的函数的情况没有被 numpydoc 风格指南特别提及,仔细注意它只解决 函数的情况 return 值:

Sections - numpydoc docstring guide

  1. Returns

Explanation of the returned values and their types. Similar to the Parameters section, except the name of each return value is optional. The type of each return value is always required

因此在正式的Python术语中,returns None returns 的函数没有任何价值,因为在这种情况下 None 表示缺少值,因此 numpydoc 指南没有提及这种特殊情况:

3.2. The standard type hierarchy, Data Model

None

  • This type has a single value(...) It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything.

由于缺少样式指南,所以我们可以尝试在 numpy 文档中搜索 returns None 的函数,看看它是如何完成的。一个很好的例子是 numpy.copyto,实际上 docstring 部分 对应于 Return 是不存在的。

不应将方法及其文档字符串的详细文档与可能给出简短文本描述的列表相混淆。将上述 numpy.copyto 示例的详细文档与 Logic functions - comparison 中的列表进行比较,后者确实对 return 进行了文字描述,但省略了签名中的所有类型提示。

为了完整起见,我们可以在这种情况下引用 Google 风格指南:

3.8.3 Functions and Methods, Google Python Style Guide

Returns: (or Yields: for generators) (...) If the function only returns None, this section is not required.

最后,问题中的示例可以用 NumPy 样式的文档字符串编写为:

def foo(list_of_items: list, the_path: str) -> None:
    """Simple function writes list_of_items to the_path.

    Parameters
    ----------
        list_of_items : list of str
            Describes list_of_items.
        the_path : str
            Describes the_path.
    """

    file = open(the_path)
    file.write(list_of_items[1])
    file.close()

或使用 Google 风格的文档字符串:

def foo2(list_of_items: list[str], the_path: str) -> None:
    """Simple function writes list_of_items to the_path.

    Params:
        list_of_items (list[str]): Describes list_of_items.
        the_path (str): Describes the_path.
    """

    file = open(the_path)
    file.write(list_of_items[1])
    file.close()