James Lin James Lin - 1 month ago 9
Python Question

Python how to "borrow" docstring from another class?

Background

I am using django-rest-swagger to display the API documentation, the official way for swagger is to use the docstring from the view.

Purpose

A lot of documentation as docstring are done in the

Model
class, so I would like to "borrow" the docstring from the
Model
class into the
APIModelView
class, without physically copying the docstring.

Eg.

class Model(models.Model):
"""
Very comprehensive docstring...
"""

field_1 = ...
field_2 = ...


class APIModelView(ModelView):
"""
<borrow from the model class>
"""
model = Model


Extension

@Martijn Pieters' answer worked fine on class level docstring

I just realised swagger actually uses the instance method docstring, eg.

class APIModelView(ModelView):
def list(self, request, *args, **kwargs):
__doc__ = Model.__doc__
...


but above doesn't work...

Answer

You can set the __doc__ attribute when creating the class; simply make that a copy of the original model:

class APIModelView(ModelView):
    __doc__ = Model.__doc__
    model = Model

Without an actual docstring on a class, any already-present __doc__ attribute is retained.

Comments