【问题标题】:How to document/docstring a function whose argument/return type is dynamic?如何记录/文档字符串参数/返回类型是动态的函数?
【发布时间】:2021-10-15 08:55:23
【问题描述】:

pickle.dump()pickle.load() 函数为例。

如何指示/记录/文档字符串pickle.dump()接收的参数类型或pickle.load()返回的值的类型?

这是Google Style Python Docsting 的示例。如您所见,普通函数的参数类型和返回类型是静态的并且明确记录在案:

def function_with_types_in_docstring(param1, param2):
"""Example function with types documented in the docstring.

`PEP 484`_ type annotations are supported. If attribute, parameter, and
return types are annotated according to `PEP 484`_, they do not need to be
included in the docstring:

Args:
    param1 (int): The first parameter.
    param2 (str): The second parameter.

Returns:
    bool: The return value. True for success, False otherwise.

.. _PEP 484:
    https://www.python.org/dev/peps/pep-0484/

"""

但有时参数/返回类型是动态的。甚至 pickle.py 也没有提供记录其函数的参数/返回对象类型的示例。

【问题讨论】:

    标签: python docstring


    【解决方案1】:

    只有部分示例显示了文档字符串中静态定义的返回类型。下面的示例来自问题中发布的链接,是通过类型提示在函数签名中指示返回类型的示例。

    有几种方法可以表示多种类型(例如Union[int, str, float]),因此请选择适合您的场景的方法。

    def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
        """Example function with PEP 484 type annotations.
    
        Args:
            param1: The first parameter.
            param2: The second parameter.
    
        Returns:
            The return value. True for success, False otherwise.
    
        """
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      相关资源
      最近更新 更多