How to add constant string to __doc__ for all class methods?

588 views Asked by At

I have code that looks like this:

constString = """
Default docstring info:
    1
    2
    3"""

class A():

    def A1():
        """
        First unique docstring.
        """
        pass

    def A2():
        """
        Second unique docstring.
        """
        pass
B = A()
print(B.A1.__doc__)

If I run this code I recive output:

First unique docstring.

Second unique docstring.

But I want to replace method's docstring by adding constString for all methods in class A. The output must looks like this:

First unique docstring.
Default docstring info:
1
2
3

Second unique docstring.
Default docstring info:
1
2
3

How I can do it?

2

There are 2 answers

2
Steve Jessop On BEST ANSWER

An instancemethod's docstring is taken from the underlying function, which is why B.A1.__doc__ += constString doesn't work. However:

B.A1.__func__.__doc__ += constString
0
Martijn Pieters On

Function docstrings are writable; just assign to function.__doc__; here is a decorator that adds a string to the docstring of all methods on a class:

import inspect

def add_documentation(doc):
    if not doc.startswith('\n'):
        doc = '\n' + doc

    def decorator(cls):
        for func in filter(inspect.isfunction, vars(cls).values()):
            func.__doc__ += doc
        return cls

    return decorator

Use this like so:

@add_documentation(constString)
class A:
    def A1(self):
        """
        First unique docstring.
        """
        pass

    def A2(self):
        """
        Second unique docstring.
        """
        pass

The decorator works in both Python 2 and 3 and will only affect methods defined directly on the class, not on any base classes.