简体   繁体   English

Python 字典 output 的文档字符串文档

[英]Python docstring documentation for dictionary output

What is the recommended way to document a dictionary (dict) output in python docstring for a function?在 function 的 python 文档字符串中记录字典 (dict) output 的推荐方法是什么?

I was looking at a few tutorials including this from datacamp but I can't seem to find a good example.我正在查看一些教程,包括来自datacamp的教程,但我似乎找不到一个很好的例子。

def example_function(arg1: str, arg2: list) -> dict(str, dict):
    '''
    Returns a dictionary of examples

    Args:
        arg1(str): description of argument 1
        arg2(list): description of argument 2

    Returns:
        dict(str, dict): dictionary of examples
        <example of output>

For instance, I want to show that the output of the above function has the following structure, where key1 and key2 will always be in the output例如,我想证明上述 function 的 output 具有以下结构,其中key1key2将始终在 output

{
    "example": {
        "key1": "value1",
        "key2": "value2"
    }
}

Thank you in advance, would be great if I could have some reference links as well: :)提前谢谢你,如果我也能有一些参考链接那就太好了::)

First note that this is not called "docstring documentation" but "type hints".首先请注意,这不是“文档字符串文档”而是“类型提示”。
This is exactly what you want: https://www.python.org/dev/peps/pep-0589/ (This PEP is accepted as of Python 3.8)这正是您想要的: https://www.python.org/dev/peps/pep-0589/ (此 PEP 自 ZA7F5F35426B927411FC92331B56382173 起接受)
Further reading: the typing module: https://docs.python.org/3/library/typing.html进一步阅读:打字模块: https://docs.python.org/3/library/typing.html
This is an example code snippet:这是一个示例代码片段:

from typing import TypedDict

class ExampleDataDict(TypedDict):
    key1: str
    key2: str

class ExampleDict(TypedDict):
    example: ExampleDataDict

d: ExampleDict = {
    "example": {
        "key1": "value1",
        "key2": "value2"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM