Chilipp / docrep

A Python Module for intelligent reuse of docstrings
Apache License 2.0
30 stars 4 forks source link

Reuse docstring from Class doc #2

Closed mennthor closed 7 years ago

mennthor commented 7 years ago

I tried a bit more and again I'm stuck. I usually document the __init__ method in the class docstring rather than in __init__ itself.

So I tried

import docrep
d = docrep.DocstringProcessor()

@d.get_sectionsf("A")
@d.dedent
class A():
    """
    Docstring from A

    Parameters
    ----------
    a : int
        Some value passed to _func.
    """
    def __init__(self, a):
        self._func(a)

    @d.dedent
    def _func(self, a):
        """
        Doc from _func

        Parameters
        ----------
        %(A.parameters)s
        """
        print(d.params)

        return

This gives:

SyntaxWarning: 'A.parameters' is not a valid key!
  @d.dedent

However, d.params has:

'A.parameters': 'a : int\n    Some value passed to _func.', 'A.other_parameters': ''

What works instead is just to document the __init__ method. But old habits and stuff...

Is there a way around this, or am I again just not seeing how it works? I guess the f in get_sectionsf is for function, but I don't see the difference to a class, which also has __doc__? Best, Thorben

Chilipp commented 7 years ago

Hi Thorben,

you're getting two problems here:

  1. The uppermost decorators
    @d.get_sectionsf("A")
    @d.dedent

    are called after the class has been compiled, i.e.__init__ doesn't know about the @d.get_sectionsf("A") call.

  2. in python2 (if that is important to you), docstrings of classes cannot be modified after they are compiled. Therefore you would get problems with the @d.dedent call

But you can solve this problem by using directly the __doc__ attribute of the class in combination with the dedents and get_sections method:

import docrep
d = docrep.DocstringProcessor()

class A():
    __doc__ = d.get_sections(d.dedents("""
    Docstring from A

    Parameters
    ----------
    a : int
        Some value passed to _func.
    """), "A")

    def __init__(self, a):
        self._func(a)

    @d.dedent
    def _func(self, a):
        """
        Doc from _func

        Parameters
        ----------
        %(A.parameters)s
        """
        print(d.params)

        return
mennthor commented 7 years ago

That works :) Thanks again for the detailed answer 👍

Chilipp commented 7 years ago

You're welcome!