Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String manipulation in Python docstrings

I've been trying to do the following:

#[...]
    def __history_dependent_simulate(self, node, iterations=1,
                                     *args, **kwargs):
        """
        For history-dependent simulations only:
        """ + self.simulate.__doc___

What I tried to accomplish here is to have the same documentation for this private method as the documentation of the method simulate, except with a short introduction. This would allow me to avoid copy-pasting, keep a shorter file and not have to update the documentation for two functions every time.

But it doesn't work. Does anyone know of a reason why, or whether there is a solution?

like image 672
Ram Rachum Avatar asked Oct 05 '09 09:10

Ram Rachum


People also ask

What do docstrings do in Python?

A Python docstring is a string used to document a Python module, class, function or method, so programmers can understand what it does without having to read the details of the implementation. Also, it is a common practice to generate online (html) documentation automatically from docstrings.

Should I use docstrings in Python?

Docstrings are for people who are going to be using your code without needing or wanting to know how it works. Docstrings can be turned into actual documentation.

What are the three types of docstrings?

Docstrings can be further broken up into three major categories: Class Docstrings: Class and class methods. Package and Module Docstrings: Package, modules, and functions. Script Docstrings: Script and functions.

What are docstrings in functions?

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings.


2 Answers

A better solution is probably to use a decorator, eg:

def add_docs_for(other_func):  
    def dec(func):  
        func.__doc__ = other_func.__doc__ + "\n\n" + func.__doc__
        return func
    return dec

def foo():
    """documentation for foo"""
    pass

@add_docs_for(foo)
def bar():
    """additional notes for bar"""
    pass

help(bar) # --> "documentation for foo // additional notes for bar"

That way you can do arbitrary manipulations of docstrings.

like image 134
Anthony Towns Avatar answered Oct 01 '22 05:10

Anthony Towns


I think this section makes it pretty clear:

What is a Docstring?

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the doc special attribute of that object.

So, it's not an expression that evaluates into a string, it's a string literal.

like image 22
unwind Avatar answered Oct 01 '22 05:10

unwind