如何为dict的dict添加python docstring

时间:2018-08-02 20:19:00

标签: python python-3.x pycharm docstring

我有一个对象,它是命令的命令。我想告诉我的编辑器这个对象是这样,我该怎么做?目前我有:

def do_somthing(dict_of_dicts):
    """
    :type dict_of_dicts: dict of dict
    """

    for key, value in dict_of_dicts.items():
            for key2, value2 in value.items():
                print('Key')

但是,我的编辑器(Pycharm)似乎没有在注册它。

4 个答案:

答案 0 :(得分:3)

您可以使用Dict使用类型提示来实现此目的:

from typing import Dict, Any

def do_somthing(dict_of_dicts: Dict[Any, Dict]):
    """
    :type dict_of_dicts: Dict[Any, Dict]
    """

    for key, value in dict_of_dicts.items():
            for key2, value2 in value.items():
                print('Key')

答案 1 :(得分:2)

我不使用PyCharm,但是……它可以理解类型注释,对吗?因此,将其指定为注释:

from typing import Dict, Any

def do_something(dict_of_dicts: Dict[Any, Dict[Any, Any]]):
    # ...

或者,您甚至可以定义通用的DictOfDict类型(外键,内键和内值的通用类型):

from typing import Dict, Any, TypeVar, Generic:

K1, K2, V = TypeVar('K1'), TypeVar('K2'), TypeVar('V')
class DictOfDicts(Dict[K1, Dict[K2, V]]): ...

def do_something(dict_of_dicts: DictOfDicts[Any, Any, Any]):
    # ...

答案 2 :(得分:0)

您可能已经找到了答案,但对于偶然发现此主题的其他人来说:

试试这个,不需要导入typing

dict[dict]

它将在文档字符串中显示为:

 Dict[dict]

就您的示例而言:

def do_somthing(dict_of_dicts):
    """
    :type dict_of_dicts: dict[Any, dict]
    """

    for key, value in dict_of_dicts.items():
            for key2, value2 in value.items():
                print('Key')

答案 3 :(得分:-1)

您还可以添加param

def do_somthing(dict_of_dicts):
    """
    :param dict_of_dicts: A dictionary of dictionaries.
    :type dict_of_dicts: dict of dict
    """

for key, value in dict_of_dicts.items():
        for key2, value2 in value.items():
            print('Key')

我建议阅读这篇文章:https://thomas-cokelaer.info/tutorials/sphinx/docstring_python.html