There is a question about Inherit docstrings in Python class inheritance, but the answers there deal with method docstrings.
My question is how to inherit a docstring of a parent class as the __doc__
attribute. The usecase is that Django rest framework generates nice documentation in the html version of your API based on your view classes' docstrings. But when inheriting a base class (with a docstring) in a class without a docstring, the API doesn't show the docstring.
It might very well be that sphinx and other tools do the right thing and handle the docstring inheritance for me, but django rest framework looks at the (empty) .__doc__
attribute.
class ParentWithDocstring(object):
"""Parent docstring"""
pass
class SubClassWithoutDoctring(ParentWithDocstring):
pass
parent = ParentWithDocstring()
print parent.__doc__ # Prints "Parent docstring".
subclass = SubClassWithoutDoctring()
print subclass.__doc__ # Prints "None"
I've tried something like super(SubClassWithoutDocstring, self).__doc__
, but that also only got me a None
.
You can also do it using
@property
You can even overwrite a docstring.
One caveat, the property can't be inherited by other classes evidently, you have to add the property in each class that you want to overwrite the docstring.
Bummer! But definitely easier than doing the meta class thing!
Since you cannot assign a new
__doc__
docstring to a class (in CPython at least), you'll have to use a metaclass:Yes, we jump through an extra hoop or two, but the above metaclass will find the correct
__doc__
however convoluted you make your inheritance graph.Usage:
The alternative is to set
__doc__
in__init__
, as an instance variable:Then at least your instances have a docstring:
As of Python 3.3 (which fixed issue 12773), you can finally just set the
__doc__
attribute of custom classes, so then you can use a class decorator instead:which then can be applied thus:
The simplest way is to assign it as a class variable:
It's manual, unfortunately, but straightforward. Incidentally, while string formatting doesn't work the usual way, it does with the same method:
In this particular case you could also override how REST framework determines the name to use for the endpoint, by overriding the
.get_name()
method.If you do take that route you'll probably find yourself wanting to define a set of base classes for your views, and override the method on all your base view using a simple mixin class.
For example:
Note also that the
get_name
method is considered private, and is likely to change at some point in the future, so you would need to keep tabs on the release notes when upgrading, for any changes there.