act*_*nda 6 python docstring typing
是否有typing在文档字符串中使用类型别名或对象的最佳实践?
这个问题可能会吸引基于意见的答案。但也可能是有一个被广泛接受的约定或对特定解决方案的外部工具支持。
示例:函数返回一个包含字符串键和值的字典。您会将什么类型放入“退货”部分下的文档字符串中?(我使用的是熊猫风格的文档字符串。)
选项1:只是说它是一个字典。
import typing
strstrdict = typing.Dict[str, str]
def foo() -> strstrdict:
'''
bla bla
Returns
-------
dict
A dictionary with string keys and values that represents ...
'''
# code
Run Code Online (Sandbox Code Playgroud)
选项 2:使用类型别名。
import typing
strstrdict = typing.Dict[str, str]
def foo() -> strstrdict:
'''
bla bla
Returns
-------
strstrdict
A dictionary with string keys and values that represents ...
'''
# code
Run Code Online (Sandbox Code Playgroud)
选项 3:放入"typing.Dict[str, str]"文档字符串。
import typing
strstrdict = typing.Dict[str, str]
def foo() -> strstrdict:
'''
bla bla
Returns
-------
typing.Dict[str, str]
A dictionary with string keys and values that represents ...
'''
# code
Run Code Online (Sandbox Code Playgroud)
选项4:别的?
编辑 1
“我正在使用熊猫风格的文档字符串”你是在寻找这种风格的答案还是一般的答案?
我想最佳答案将尽可能涵盖一般和特定情况。我提到了pandas样式以明确为什么有“返回”部分而没有像“:param:”这样的说明。我对答案的风格并没有死心塌地。
你真的在你的文档中包含了别名,即用户能发现别名
strstrdict是什么吗?
目前没有关于别名的文档。用户可以查看themodule.strstrdict。我对这里的建议持开放态度。
编辑 2
我链接到的样式指南巧合地提到了一个带有字符串键和值的字典。我正在寻找的答案也应该涵盖这样的情况:
from typing import Any, Callable, ContextManager, Iterable
ContextCallables = ContextManager[Iterable[Callable[[int, int], Any]]]
def foo() -> ContextCallabes:
'''
bla bla
Returns
-------
???
some description
'''
# code
Run Code Online (Sandbox Code Playgroud)
由于您明确提到了您所遵循的文档风格约定,因此基于意见的答案不应该有问题。
我们可以查看 pandas 文档字符串指南中有关参数类型的部分:
对于复杂类型,定义子类型。对于
dict和tuple,由于存在不止一种类型,我们使用括号来帮助读取类型(大括号用于dict,普通括号用于tuple)。
这意味着您应该记录Dict[str, str]如下:
Returns
-------
dict of {str : str}
Some explanation here ...
Run Code Online (Sandbox Code Playgroud)
您可以查看文档以获取更多示例,包括其他类型。
| 归档时间: |
|
| 查看次数: |
439 次 |
| 最近记录: |