是否有标准的python方式来表示函数的参数类型和返回类型?
我正在寻找一个符号,它是:
-
help()
可识别 - ide可识别 PEP中描述的
- (最好)
我已经看到了一些例子,像这样的reSt语法:
"""replaces template place holder with values
:param timestamp: formatted date to display
:type timestamp: str or unicode
:param priority: priority number
:type priority: str or unicode
:param priority_name: priority name
:type priority_name: str or unicode
:param message: message to display
:type message: str or unicode
:returns: formatted string
:rtype: str or unicode
"""
但是,我不确定这种格式是否被官方支持。
主要有3/4种格式在竞争Python文档字符串。请参阅本教程了解概述。旧的格式(现在已不再使用)是基于Javadoc样式的Epydoc的Epytext。比较流行的可能是用于Sphinx格式的reStructuredText (reST)。Google样式也很常用。当然还有Numpydoc灵感来自Google风格。
关于什么应该是官方的/标准的方式,你可以参考这个话题。
每种格式都有自己的方式来表示参数类型和返回类型。下面是一些例子:
- Epytext/Javadoc
"""
@param param1: Description of param1
@type param1: type of param1
@return: description of returned value
@rtype: type of returned value
"""
- """
:param param1: Description of param1
:type param1: type of param1
:return: description of returned value
:rtype: type of returned value
"""
——谷歌
"""
Args:
param1(int): Description of parameter `param1`.
param2(str, optional): Description of a parameter. Defaults to None.
Returns:
bool: True or False depending on the result.
"""
——Numpydoc
"""
Parameters
----------
param1 : int
Description of parameter `param1`.
param2 : {'value1', 'value2'}
Description of a parameter with two possible values.
Returns
-------
int
Description of the returned value
"""
转换
"""
:param param1: Description of param1
:type param1: type of param1
:return: description of returned value
:rtype: type of returned value
"""
"""
Args:
param1(int): Description of parameter `param1`.
param2(str, optional): Description of a parameter. Defaults to None.
Returns:
bool: True or False depending on the result.
"""
"""
Parameters
----------
param1 : int
Description of parameter `param1`.
param2 : {'value1', 'value2'}
Description of a parameter with two possible values.
Returns
-------
int
Description of the returned value
"""
请注意,如果您没有文档字符串,或者您想更改Python项目的文档字符串格式,您可以使用Pyment。
我敢说,没有PEP描述这一点;PEP257是关于文档字符串的,但实际上是非常小的(标准库文档字符串很少像你的那么精确)。
这两个相互竞争的标准是您已经找到的,在Sphinx中实现的标准,以及更详细(但也更可读)的NumPy约定,在Sphinx的numpydoc
扩展中实现。