【问题标题】:How do I write a docstring for the following Python function? [closed]如何为以下 Python 函数编写文档字符串? [关闭]
【发布时间】:2019-10-09 03:01:42
【问题描述】:

假设我有以下功能:

def get_matrix(*args, arbitrary=True):
    if arbitrary == True:
        return np.random.randint(-10,10, size=[args[0],args[1]])
    else:
        return np.array(args[0])

所以函数要么

  1. 生成矩阵(如果任意 == True);在这种情况下,它需要两个 int 参数。

  1. 将数组(如果任意 == False)(由元组或列表表示)转换为 numpy 的数组

如何为这个函数编写简洁易读的文档字符串? (最好保留numpy's docstring style)Numpy 对如何记录 *args 和 **kwargs 没有任何意见。 (或者也许他们做到了,但到目前为止我还没有发现任何东西)

【问题讨论】:

    标签: python docstring


    【解决方案1】:

    任何对您的项目有意义的东西。 *args 的通用术语是“位置参数”,通常您会希望将它们单独称为“nth 位置参数”。关键字参数**kwargs 通常应根据具体情况使用可接受的键和值单独提及,除非您方法中的 kwargs 充当其他方法中 kwargs 的代理,在这种情况下,您也可以写“关键字参数与[其他方法]相同,请参阅该文档了解更多详细信息”。


    在这种情况下,您给出的示例很难,主要是因为这是一种不好的做法-方法应该做一件事;如果您有一个方法根据标志的值做两件不同的事情,那么为什么不只拥有两个方法并让调用者显式调用其中一个呢? (延伸阅读:PEP 20

    Numpy 的文档标准似乎走得更远,通常完全避开通用的**kwargs(支持显式命名的关键字),并且更喜欢可以在文档字符串中引用的命名位置参数。您链接的文档没有提供有关该主题的明确建议,但我倾向于将 *args 作为“变量名”(保留星号以表示它们是位置参数),并将 integers 作为值(注意复数),然后在描述中明确指出它表示位置参数。或者,我在下面所做的,只是将其明确列为“位置参数”(毕竟,这种文档字符串格式对类型提示没有用处)。

    这主要是个人喜好,但我会这样记录您的功能:

    def get_matrix(*args, arbitrary=True):
        """
        If `arbitrary` is True (default), generates a random matrix, 
        with x and y bounds represented by the first two given 
        positional args, and returns it.
    
        If `arbitrary` is False, then instead coerces the first positional
        argument into a np.array, and returns that.
    
        parameters
        ----------
        positional args: ints
            purpose depends on the value of arbitrary (see above)
        arbitrary: bool
            determines the behavior of the function (see above)
    
        returns
        -------
        if arbitrary is true, a random 2D array of defined size.
        otherwise, the first positional argument coerced to a np.array
        """
        if arbitrary == True:
            return np.random.randint(-10,10, size=[args[0],args[1]])
        else:
            return np.array(args[0])
    

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2021-01-13
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多