简体   繁体   English

可以使用 python 3 中的类型提示生成文档字符串吗?

[英]Can type hint in python 3 be used to generate docstring?

We can indicate the types of function parameters using docstring in python:我们可以在 python 中使用 docstring 指示函数参数的类型:

def f1(a):
    """
    :param a: an input.
    :type a: int
    :return: the input integer.
    :rtype: int
    """
    return a

For f1 , autodoc generates the following document:对于f1 ,autodoc 生成以下文档:

fun1(a)
    Parameters : a (int) – an input.
    Returns    : the input integer.
    Return type: int

In python 3, the types can be indicated by type hint as well:在 python 3 中,类型也可以通过类型提示来指示:

def f2(a: int):
    """
    :param a: an input.
    :return: the input integer.
    :rtype: int
    """
    return a

When we run autodoc, it puts the type by the parameter declaration, but not in the description:当我们运行 autodoc 时,它通过参数声明放置类型,而不是在描述中:

f2(a: int)
    Parameters : a – an input.
    Returns    : the input integer.
    Return type: int

Would it be possible to generate the documentation as f1 using annotation instead of docstring?是否可以使用注释而不是文档字符串将文档生成为f1 I'm using python 3.6.我正在使用 python 3.6。 Thank you!谢谢!

Not yet, from what I'm aware Sphinx yet doesn't support this.还没有,据我所知,Sphinx 还不支持这一点。 The bug referenced in a comment was about the representation of the type-hints and not their positioning.评论中提到的错误是关于类型提示的表示而不是它们的定位。

I do know there's currently an extension for Sphinx that takes care of this for you though, called sphinx-autodoc-typehints .我知道目前有一个名为sphinx-autodoc-typehints的 Sphinx 扩展可以为您解决这个问题。 You could probably use that for the time being.您可能暂时可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM