我想使用 Python 文档字符串来更好地记录我的代码。
在下面的函数中,它将一个列表作为输入并将文件写入磁盘。我想知道如何将文档字符串中函数的输出记录为 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()
Run Code Online (Sandbox Code Playgroud)
关于类型提示的唯一 Python 约定是:
\n\n\n非目标,PEP 484
\n还应该强调的是,Python 将仍然是一种动态类型语言,即使按照惯例,作者也不希望强制类型提示。
\n
考虑到这一点,有3 种语法用于编写 docstrings。两种语法都有自己的样式指南,请参阅numpydoc 文档字符串指南和Google Python 样式指南 - 3.8 注释和文档字符串。(相比之下,PEP 8和PEP 257没有那么具体)。
\nNonenumpydoc 风格指南没有特别提到仅返回函数的情况,请仔细注意,它仅解决返回值的函数的情况:
\n\n\n\n
\n- 退货
\n返回值及其类型的说明。与参数部分类似,不同之处在于每个返回值的名称是可选的。每个返回值的类型始终是必需的
\n
因此,在正式的Python术语中,返回的函数None不返回任何值,因为在这种情况下None意味着缺少值,因此numpydoc指南没有提到这种特殊情况:
\n\n\n没有任何
\n\n
\n- 该类型具有单个值(...),它用于表示在许多情况下不存在值,例如,它是从不显式返回任何内容的函数返回的。
\n
由于省略了样式指南,因此我们可以尝试在 numpy 文档中搜索返回的函数None来查看它是如何完成的。一个很好的例子是numpy.copyto,确实缺少对应的文档字符串部分。Return
方法及其文档字符串的详细文档不应与可能给出简短文本描述的列表相混淆。将上述示例的详细文档numpy.copyto与逻辑函数 - 比较中的列表进行比较,该列表确实以文本方式描述了返回结果,但省略了签名中的所有类型提示。
为了完整起见,我们可以引用有关此案例的 Google 风格指南:
\n\n\n3.8.3 函数和方法,Google Python 风格指南
\n返回:(或 Yields:对于生成器)\n(...) 如果函数仅返回 None,则不需要此部分。
\n
最后,问题中的示例可以使用 NumPy 风格的文档字符串编写为:
\ndef foo(list_of_items: list, the_path: str) -> None:\n """Simple function writes list_of_items to the_path.\n\n Parameters\n ----------\n list_of_items : list of str\n Describes list_of_items.\n the_path : str\n Describes the_path.\n """\n\n file = open(the_path)\n file.write(list_of_items[1])\n file.close()\nRun Code Online (Sandbox Code Playgroud)\n或者使用 Google 风格的文档字符串:
\ndef foo2(list_of_items: list[str], the_path: str) -> None:\n """Simple function writes list_of_items to the_path.\n\n Params:\n list_of_items (list[str]): Describes list_of_items.\n the_path (str): Describes the_path.\n """\n\n file = open(the_path)\n file.write(list_of_items[1])\n file.close()\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
3558 次 |
| 最近记录: |