Home > OS >  correct way to "porting" docstrings of other methods/functions/objects into a class?
correct way to "porting" docstrings of other methods/functions/objects into a class?

Time:10-21

Here is what I am doing:

class Foo:
    def __init__(self, **kwargs):
        """
        docstring of Foo.
        """
        self.sum = bar(**kwargs)
    __init__.__doc__  = bar.__doc__

def bar(a, b):
    """
    docstring of bar.
    a: int
    b: int
    """
    print(a b)

What I wanted to do: There are some calculations defined in bar. The class Foo uses bar. I would like to avoid duplicate code, i.e. I would like to avoid writing for example a: int in Foo. Thus I am trying to "port" (is this the right term?) the docstring of bar into Foo by adding that line __init__.__doc__ = bar.__doc__.

Is this the right way to do this? Am I hacking? Imagine Foo is part of API, whereas bar is the backstage subroutine. What's the correct way of displaying the docstring of bar to the user?

CodePudding user response:

You need to define bar before Foo. In your current configuration, the name bar does not exist in the global namespace when the class body is executed.

You might consider adding a newline or some sort of divider between the docs:

__init__.__doc__  = '\n'    bar.__doc__

Documentation is rarely read directly from a docstring. A better answer would be to use a tool like sphinx to generate useable documentation in a format like HTML or PDF. Instead of copy-and-pasting the documentation of bar into that of Foo.__init__, you could link to it. This would have the advantage that you would not need to rearrange the objects in the global namespace.

The popular plotting library matplotlib is a great example of your exact usecase. It has many functions, like matplotlib.pyplot.subplots, which passes through is remaining arguments (fig_kw) to matplotlib.pyplot.figure. Looking at the source for the docstring, we see:

**fig_kw
    All additional keyword arguments are passed to the
    `.pyplot.figure` call.

The backticks generate a link in sphinx. You can write the docstring of Foo.__init__ in a similar manner:

"""
docstring of Foo.

Parameters
----------
**kwargs
    Arguments passed through to `bar`.
"""
  • Related