【问题标题】:Is there a standard docstring format to show what signature is expected for an argument that takes a function?是否有标准的文档字符串格式来显示需要函数的参数的签名?
【发布时间】:2019-05-30 16:52:06
【问题描述】:

我的__init__ 方法接受另一个函数作为参数,称为func_convert

class Adc:
    """Reads data from ADC

    """
    def __init__(self, func_convert):
        """Setup the ADC

        Parameters
        ----------
        func_convert : [???]
            user-supplied conversion function
        """
        self._func_convert = func_convert

    def read(self):        
        data = 0 #some fake data
        return self._func_convert(data)

参数func_convert 允许在实例化时提供一次自定义缩放函数,该函数在每次读取时调用以转换数据。该函数必须接受一个 int 参数并返回一个浮点数。一个可能的例子是:

def adc_to_volts(value):
    return value * 3.0 / 2**16 - 1.5

adc = Adc(adc_to_volts)
volts = adc.read()

__init__ 文档字符串的参数部分中,是否有一种标准方法来记录func_convert 的预期签名?如果它有所作为,我使用的是 numpy docstring 样式(我认为)。

【问题讨论】:

    标签: python docstring


    【解决方案1】:

    我不知道文档字符串是否存在这个标准 - 你当然可以用简单的句子解释函数需要什么,但我假设你想要一个标准的、文档生成器友好的方式来做到这一点。

    如果您不介意切换工具,可以使用类型提示和来自typing moduleCallable 对象:

    from typing import Callable
    
    class Adc:
        """
        Reads data from ADC
    
        """
        def __init__(self, func_convert: Callable[[int], float]) -> None:
            self._func_convert = func_convert
    
        def read(self):        
            data = 0  # some fake data
            return self._func_convert(data)
    

    【讨论】:

      【解决方案2】:

      如果你想遵循 numpy 的 docstring 风格,有一些来自 numpy 的例子展示了函数参数是如何描述的:

      1)

      apply_along_axis(func1d, axis, arr, *args, **kwargs)
          ...
      
          Parameters
          ----------
          func1d : function (M,) -> (Nj...)
              This function should accept 1-D arrays. It is applied to 1-D
              slices of `arr` along the specified axis.
      

      2)

      apply_over_axes(func, a, axes)
          ...
      
          Parameters
          ----------
          func : function
              This function must take two arguments, `func(a, axis)`.
      

      3)

      set_string_function(f, repr=True)
          ...
      
          Parameters
          ----------
          f : function or None
              Function to be used to pretty print arrays. The function should expect
              a single array argument and return a string of the representation of
              the array. If None, the function is reset to the default NumPy function
              to print arrays.
      

      TLDR:它们是手动描述的,没有任何特殊的语法或指南。如果你的目标是创建类似于 numpy 的文档字符串,你可以用任何你想要的方式来描述它们。但我强烈建议关注@jfaccioni answer 并使用类型提示。

      【讨论】:

      • 我认为Callable 解决方案是最安全的选择,但您的sn-ps 也很有帮助!基于第一个,我决定在文档字符串func_convert : function(int) -> (float) 中做这样的事情。如果我能接受两个答案,我会的!
      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 2015-07-20
      • 2013-01-29
      • 1970-01-01
      • 2019-08-05
      • 2021-08-14
      • 2011-11-08
      • 1970-01-01
      相关资源
      最近更新 更多