问题描述
我想使用python docstring更好地记录我的代码。 在下面的功能中,它将列表作为输入并将文件写入磁盘。我想知道如何在docstring中将函数的输出记录为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
还应该强调的是,Python 仍将是一种动态类型的语言,即使按照惯例,作者也不希望强制类型提示。
考虑到这一点,有3 syntax for writing docstrings。两种语法都有自己的风格指南,请参阅 numpydoc docstring guide 和 Google Python Style Guide - 3.8 Comments and Docstrings。 (相比之下,PEP 8 和 PEP 257 没有那么具体。
numpydoc 风格指南没有特别提到只返回 None
的函数的情况,注意它只解决了返回值的函数的情况:
Sections - numpydoc docstring guide
- 退货
返回值及其类型的说明。类似于参数部分,除了每个返回值的名称是可选的。 每个返回值的类型总是需要的
因此在正式的 Python 术语中,返回 None
的函数不返回任何值,因为在这种情况下 None
表示没有值,因此 numpydoc 指南没有提到这个特殊情况:
3.2. The standard type hierarchy,Data Model
无
- 这种类型有一个单一的值(...) 它在很多情况下用于表示没有一个值,例如,它是从没有明确说明的函数中返回的返回任何东西。
由于缺少样式指南,所以我们可以尝试在 numpy 文档中搜索返回 None
的函数以查看它是如何完成的。一个很好的例子是 numpy.copyto
并且确实没有对应于 Return
的 docstring 部分。
方法及其文档字符串的详细文档不应与可能给出简短文本描述的列表混淆。将上述 numpy.copyto
示例的详细文档与 Logic functions - comparison 中的列表进行比较,后者确实以文本方式描述了返回,但省略了签名中的所有类型提示。
为了完整起见,我们可以在此案例中引用 Google 风格指南:
3.8.3 Functions and Methods,Google Python Style Guide
回报:(或收益:对于发电机) (...) 如果函数只返回 None,则不需要此部分。
最后,问题中的示例可以用 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()