Will Be
Will Be

Reputation: 119

Docstring as a variable or function?

I have started a little project developing a number of convenience classes that operate with sklearn.

Most of them are pretty short due to the use of sklearn parent classes, but I end up with huge Docstrings that reduce the readability whenever I try to make a small change or inspect the class.

Is there any official way to preserve the properties of a Docstring (i.e to be usable with ?, help() or __doc__) without "tricking" Python and not using a multiline comment in the class?

The only way I have come up so far is:

doc_foo = """foo docstring"""
doc_bar = """bar docstring"""

class foo(object):

    __doc__ = doc_foo

    def __init__(self):
        pass

    def bar(self):
        pass

However, this works only with classes and not in methods or functions.

Upvotes: 2

Views: 104

Answers (1)

chepner
chepner

Reputation: 531075

You can set a function's docstring after it has been defined.

def bar(self):
    pass

bar.__doc__ = doc_bar

You can facilitate this with a decorator:

def set_doc(docstr):
    def _(f):
        f.__doc__ = docstr
        return f
    return _


@set_doc(doc_bar)
def bar(self):
    pass

Upvotes: 3

Related Questions