3

I have a Django-REST-framework class based view/endpoint that looks like that:

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

I would like to integrate the constant INPUT_FORMAT in the docstring, since it is used in several places in the code. I tried this and this but with no success. Is it possible?

bolino
  • 867
  • 1
  • 10
  • 27
  • I have edited my question to contain a solution - but please be aware, you're better off not doing this at all and just hard coding your docstrings. I've explained why in the answer. – Micheal J. Roberts Feb 27 '20 at 11:28

1 Answers1

1

You don't need any DRF knowledge, I think this is more an understand of how classes work in Python and how class inheritance works, and how classes can be initilised and how attributes can be set using the __init__() function. However, that being said:

In my opinion such use of docstrings would be unexpected.

Docstrings are used to explain what does an object, explain its parameters or propose usage of the object.

In your case you are saying something about the execution of your function, not how does it works so I wouldn't create it dynamically.

It is far better to keep the documentation clear and concise.

I'd also reference here: Google Styleguide: Comments & Docstrings

The only way I can see this being done is as follows:

Monkey patching the help() function. But...just say no to monkey patching.

Or, dynamic docstring creation:

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

The above solution however, does not work for help(). And can only be accessed via the View.__doc__ attribute. And therefore, as stated, would not be idiomatic or standard Python code.

I think although you see it as a good idea, think of how much time you have potentially wasted in trying to figure out creating a dynamic docstring. Was it worth it?

Micheal J. Roberts
  • 3,735
  • 4
  • 37
  • 76