【问题标题】:Conveying docstrings for certain python functions为某些 python 函数传递文档字符串
【发布时间】:2015-09-02 05:10:06
【问题描述】:

我有一个通用的文档字符串格式,我在创建函数时会尝试遵循这些格式。我简要介绍了该函数的作用,然后简要说明了它的输入和输出的类。

def cuberoot4u(number):
    """Returns the cube root of number.

    cuberoot4u(float) -> float

    """
    return pow(number, 1/3)

所以在这种情况下,cuberoot4u 将浮点数作为输入并返回浮点数作为输出。

如果函数将 .txt 文件作为输入并以字符串形式输出内容,我怎样才能最好地使用文档字符串向用户传达函数所需的输入类别?

def getText(filename):
    """Reads the file filename and returns the content.

    getText(?????) -> str
    """
    fd = open(filename)
    text = fd.read()
    fd.close()
    return text

最好说getText(filename.txt) -> str 还是有一个特定的类名,就像字符串是'str'而整数是'int'?

另外,对于像这个例子中没有明确定义输出的函数怎么办:

def commandmenu():
    """Begin some random menu which does stuff.

    commandmenu() -> ??????
    """


    while 1:
        someuserinput = input("Enter a command: ")
        if someuserinput == 'this':
            pass
        elif someuserinput == 'that':
            pass
        else:
            print('u suck')
    return None

所以在这种情况下,输入函数没有初始输出,因为它会在执行某些操作之前导致用户输入。什么最适合????如果这样的功能变得越来越细致,可能会根据对用户的提示等导致多个不同的输出?

【问题讨论】:

    标签: python docstring


    【解决方案1】:

    你碰到了通常被称为抽象中的一个洞。在您的情况下,抽象是每个指定参数类型的函数足以记录它。大多数语言(或者可能是所有语言),尤其是 Python,都没有足够强大的类型系统来实现它。

    考虑一个类似于第一个函数,但计算平方根的函数:

    def squareroot4u(number):
        """Returns the cube root of number.
    
        squareroot4u(float) -> float
    
        """
        return pow(number, 1/2)
    

    显然,只有当number 为非负数时,返回类型才为float,否则应为complex。 Python(与某些面向科学的语言不同)没有单独的非负数类型,因此您必须另外指定一个强制执行它的contract

    def squareroot4u(number):
        """Returns the cube root of number.
    
        squareroot4u(number: float) -> float
    
        precondition: number >= 0
        raises ValueError otherwise
        """
        return pow(number, 1/2)
    

    我个人使用Sphinx 进行记录,其格式看起来像

    def squareroot4u(number):
        """Returns the cube root of number.
    
        :param number: a non-negative number, raises ``ValueError`` otherwise
        :type number: ``float``
        :return: square root of the input
        :rtype: ``float``
        """
        return pow(number, 1/2)
    

    第二个功能:

    def getText(filename):
        """Reads the file filename and returns the content.
    
        :param filename: a path to a text file 
                         (raises ``WhateverError``/blows ups the monitor otherwise)
        :type filename: ``str``
        :returns: file contents
        :rtype: ``str``
        """
    

    请注意,当 Python 文档字符串中的类型可以从上下文中推断出来时,它们通常会被省略(例如,除了str 之外,filename 还可以是什么?)

    现在有了第三个函数,除了类型和契约之外,你还有副作用。这些应该记录在函数的一般描述中(如果它们是运行此函数的主要点),或者记录在注释/警告中(如果它们只是要记住的东西)。例如(再次使用Sphinx 语法):

    def commandmenu():
        """Begin some random menu which does stuff.
        Shows an input prompt and awaits user input.
    
        .. warning::
    
            May or may not randomly format your hard drive during full moon.
        """
    

    在其他语言(例如 Haskell)中,一些副作用可以表示为类型(单子)并进行静态检查。例如,标准库中有一个与您的getText 类似的函数,它有一个类型

    readFile :: FilePath -> IO String
    

    而不仅仅是String,这意味着它对其参数进行一些纯粹的操作(也就是说,对于相同的输入总是返回相同的输出并且没有副作用)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2023-02-04
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多