如何在python docstring中指定不同的返回类型

时间:2017-07-10 06:01:39

标签: python python-sphinx docstring

我目前正在使用Sphinx和autodoc插件为我的python包编写文档。 对于函数返回值,我可以例如写lapply(1:9, function(x) 2*x + -1:0) 告诉sphinx有一个类型为int的返回值,名为count。

我现在有一个函数可以让我的数据库中的项目的前辈:

:returns: int: count

如您所见,它会提取原始项目,并返回类def get_previous_release(release_id): """ Holt Vorgängeritem eines Items mit der ID release_id :param release_id: ID des items für das Release :type release_id: int """ if not isinstance(release_id, int): raise ValueError('get_previous_release expects an Integer value for the parameter release_id') try: release = my_queries.core.get_by_id(release_id) except IndexError: raise LookupError('The item with id {} could no be found'.format(release_id)) if 'Alpha-Release' in release.name: release = AlphaRelease(release.key, release.name, release.state) elif 'Beta-Release' in release.name: release = BetaRelease(release.key, release.name, release.state) elif '-Release' in release.name: release = VRelease(release.key, release.name, release.state) else: raise TypeError('The item with the id {} does not contain \'-Release\' in the Summary ' + \ 'and is therefore not considered a Release') previous_release = release.get_predecessor() if not previous_release: raise LookupError('Could not find a predecessor for item with id {}'.format(release_id)) return previous_release AlphaReleaseBetaRelease的实例,具体取决于字段VRelease的内容这些物品。

在docstring中定义具有各种可能类型的返回值的最佳做法是什么?

1 个答案:

答案 0 :(得分:8)

来自Sphinx documentation

returns, return: Description of the return value.
rtype: Return type. Creates a link if possible.

您可能也会受益于:

raises, raise, except, exception: That (and when) a specific exception is raised.

所以,举个例子:

def get_previous_release(release_id):
    """ 
    Holt Vorgängeritem eines Items mit der ID release_id

    :param release_id: ID des items für das Release
    :type release_id: int
    :returns: appropriate release object
    :rtype: AlphaRelease, BetaRelease, or VRelease
    :raises ValueError: if release_id not an int
    :raises LookupError: if given release_id not found
    :raises TypeError: if id doesn't reference release
    """
    ... # your code here

不幸的是,对于多种返回类型,Sphinx语法和词汇表中没有严格或规范的选择。如果存在一个类型(例如GenericRelease),通常会指出可能返回的所有类型的超类型。但Python现在正处于Python 3中后期,它定义了一种更丰富的符号。 typing module为这些类型定义了一种不断发展的新语法,与旧的Sphinx定义无关。如果您希望使用这一新兴标准,您可以尝试以下方式:

:rtype: Union[AlphaRelease, BetaRelease, VRelease]