【问题标题】:Dynamic docstring for a Python endpointPython 端点的动态文档字符串
【发布时间】:2020-02-25 09:02:26
【问题描述】:

我有一个基于 Django-REST-framework 类的视图/端点,看起来像这样:

from rest_framework.generics import RetrieveUpdateAPIView
from .serializers import ViewSerializer

INPUT_FORMAT = {
    "input1": [9, 23, 55],
    "input2": "string",
    "input3": "boolean",
}

class View(RetrieveUpdateAPIView):
    """
    Docstring describing the endpoint.
    Would like to integrate the content of INPUT_FORMAT here.
    """
    serializer_class = ViewSerializer

    def get_object(self):
        # blahblah
        pass

我想在文档字符串中集成常量INPUT_FORMAT,因为它在代码中的多个位置使用。我试过thisthis 但没有成功。有可能吗?

【问题讨论】:

  • 我已经编辑了我的问题以包含一个解决方案 - 但请注意,你最好不要这样做,而只是硬编码你的文档字符串。我已经在答案中解释了原因。

标签: python django-rest-framework docstring


【解决方案1】:

你不需要任何 DRF 知识,我认为这更多的是了解类在 Python 中是如何工作的,类继承是如何工作的,以及如何初始化类以及如何使用__init__() 函数设置属性。但是,话虽如此:

在我看来,这样使用文档字符串是出乎意料的。

文档字符串用于解释对象的作用、解释其参数或建议对象的用法。

在你的情况下,你说的是你的函数的执行,而不是它是如何工作的,所以我不会动态地创建它。

保持文档清晰简洁会好得多。

我也会在这里参考:Google Styleguide: Comments & Docstrings

我可以看到这样做的唯一方法如下:

猴子修补了help() 函数。但是……对猴子补丁说不。

或者,动态文档字符串创建:

from rest_framework.generics import RetrieveUpdateAPIView
from .serializers import ViewSerializer

INPUT_FORMAT = {
    "input1": [9, 23, 55],
    "input2": "string",
    "input3": "boolean",
}

class View(RetrieveUpdateAPIView):
    """
    Docstring describing the endpoint.
    Would like to integrate the content of {input_1} here.
    Would like to integrate the content of {input_2} here.
    Would like to integrate the content of {input_3} here.
    """.format(**INPUT_FORMAT)
    serializer_class = ViewSerializer

    def get_object(self):
        # blahblah
        pass

但是,上述解决方案不适用于help()。并且只能通过View.__doc__ 属性访问。因此,如上所述,它不是惯用的或标准的 Python 代码。

我认为尽管您认为这是一个好主意,但请想想您在尝试创建动态文档字符串时可能浪费了多少时间。它值得吗?

【讨论】:

  • 在这种情况下,常量正好解释了对象的参数。
  • 您希望如何集成 INPUT_FORMAT 常量?
  • 这正是我的问题。
  • 我认为这从根本上来说是一个坏主意,浪费了编码时间并且违背了 python 的最佳实践。您可以修改 docstring,但在您的 Class 上调用 help() 将导致空响应。
猜你喜欢
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 2018-03-16
  • 2015-06-22
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 2021-08-28
相关资源
最近更新 更多