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

23 投票
6 回答
31264 浏览
提问于 2025-04-17 03:53

我知道参数可以是任何对象,但在文档中,明确你期望的内容是很重要的。

首先,如何指定下面这些参数的类型呢?

  • str(或者用 Stringstring?)
  • int
  • list
  • dict
  • function()
  • tuple
  • MyClass 的对象实例

其次,如何指定可以是多种类型的参数,比如一个函数可以接受一个参数,而这个参数可以是 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 中确实有某种支持来记录参数类型。下面的代码可以工作,但会在参数名称前加一个烦人的 $ 符号(因为它最初是为 php 设计的)。

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

6 个回答

5

如果你在用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?"):

另外,你可以查看函数定义的相关内容。

6

为了让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
17

其实有更好的方法。我们可以使用

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这个开发工具里,这个方法非常有效。用起来特别顺手;-)

撰写回答