繁体   English   中英

如何记录python函数参数类型?

[英]How to document python function parameter types?

我知道参数可以是任何对象,但对于文档而言,指定您期望的内容非常重要。

首先是如何指定下面的参数类型?

  • str (或使用Stringstring ?)
  • int
  • list
  • dict
  • 功能()
  • tuple
  • MyClass类的对象实例

第二,如何指定可以是多种类型的params,比如可以处理单个参数而不是intstr的函数?

请使用以下示例演示使用您提出的解决方案记录此文档所需的语法。 请注意,希望能够从文档内部超链接对“Image”类的引用。

def myMethod(self, name, image):
    """
    Does something ...

    name String: name of the image
    image Image: instance of Image Class or a string indicating the filename.

    Return True if operation succeeded or False.
    """
    return True

请注意,只要能够处理要求,欢迎您使用任何文档工具(sphinx,oxygen,...)。

更新:

它表示在doxygen中记录参数类型有一些支持。一般。 下面的代码可以工作但是会给param名称添加一个烦人的$(因为它最初是为php制作的)。

    @param str $arg description
    @param str|int $arg description

有一个更好的办法。 我们用

def my_method(x, y):
    """
    my_method description

    @type x: int
    @param x: An integer

    @type y: int|string
    @param y: An integer or string

    @rtype: string
    @return: Returns a sentence with your variables in it
    """

    return "Hello World! %s, %s" % (x,y)

而已。 在PyCharm IDE中,这有很大帮助。 它就像一个魅力;-)

您需要在Doxygen的Python文档字符串的开头添加感叹号才能正确解析它。

def myMethod(self, name, image):
    """!
    Does something ...

    @param name String: name of the image
    @param image Image: instance of Image Class or a string indicating the filename.

    @return Return True if operation succeeded or False.
    """
    return True

如果使用Python 3,则可以使用PEP 3107中描述的功能注释。

def compile(
   source: "something compilable",
   filename: "where the compilable thing comes from",
   mode: "is this a single statement or a suite?"):

另请参见函数定义

Doxygen非常适合C ++,但是如果您正在使用大多数python代码,那么您应该尝试使用sphinx 如果您选择sphinx,那么您需要做的就是关注pep8

是的,@ docu是对的 - 这是(恕我直言最好的)方式,或多或少无缝地结合两种文档方案。 另一方面,如果您还想要在doxygen生成的索引页面上执行某些操作,则需要添加

##
# @mainpage (Sub)Heading for the doxygen-generated index page
# Text that goes right onto the doxygen-generated index page

在Python代码的开头某处。

换句话说,doxygen不期望Python注释,使用##提醒它有标记。 在它需要Python注释的地方(例如在函数或类的开头),使用"""!

想想我会在这里发布这个小花絮,因为IDEA告诉我这是可能的,我从来没有被告知或读过这个。

>>> def test( arg: bool = False ) -> None: print( arg )

>>> test(10)
10

当你输入test( ,IDLE的doc-tip出现时带有(arg: bool=False) -> None这是我认为只有Visual Studio做的事情。

它并不完全是doxygen材料,但它适用于为使用您的代码的人记录参数类型。

暂无
暂无

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

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