我正在准备一个api,并使用docstrings作为文档。 api 服务选择相关的 ApiClass 方法并加入每个文档字符串以创建文档。通过这种方式,程序开发人员和 api 用户都获得了相同的文档。

我的类(class)结构是这样的:

API_STATUS = {
    1: 'some status',
    2: 'some other status message'
}

class MyApi:
    def __init__(self):
        blah blah blah

    def ApiService1(self, some_param):
        """
        here is the documentation
            * some thing
            * some other thing
        keep on explanation
        """
        do some job

    def  ApiService2(self, some_param):
        """"
        Another doc...
        """
        do some other job

我正在使用 HttpResponse 返回最终的文档字符串。因此,当我请求服务文档时,输出非常易读



到这里一切都很好,但是有一些变量,例如 API_STATUS 字典和一些列表,我希望将它们添加到文档中。但是当我将它们解析为字符串或调用 repr 函数时,所有格式都消失了



这使它不可读(因为 dict 大约有 50 个元素。)。

我不想写成 docstring(因为在 future 的更新中,相关的 dict 可能会更新而 dicstring 可能会被遗忘)

有没有办法将我的字典添加到我的响应文档字符串中(在将其作为 HttpResponse 返回之前)而不删除样式缩进?

最佳答案

使用打印:

>>> API_STATUS = {1: 'some status', 2: 'some other status message'}
>>> import pprint
>>> pprint.pprint(API_STATUS, width=1)
{1: 'some status',
 2: 'some other status message'}

关于python - 输出/打印 "readable"字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10881326/

10-11 22:57
查看更多