Search code examples
pythondocstring

Python docstring repeated param text


In a Python module (which is designed to be used in IPython Notebooks by less-technical users), I have several functions in the way of:

load_this(dt, this_filter)
load_that(dt, that_filter)
load_the_other(dt, the_other_filter)

The docstring for the dt param is the same for each function:

:param dt: date, date tuple, or datetime tuple. 
    date type args expand to start and end of day.
    eg.  date(2015, 9, 9) or
    (date(2015, 9, 9), date(2015, 9, 10)) or
    (datetime(2015, 9, 9, 12, 30), datetime(2015, 9, 9, 1))

However the docsring for x_filter params are different in each case.

I try to be as DRY as I can in my code, so the repeated docstring is grating a little. Is there any way to cross reference a docstring param in the code, but still have IPython display the full docstring.

Thanks


Solution

  • You can add docs to functions via decorator

    def mydoc(func):
        func.__doc__ = 'Here I am.'
        return func
    
    @mydoc
    def load_this(dt):
        pass
    

    Variant with custom docs

    def setdoc(docstring):
        def decor(func):
            func.__doc__ = docstring
            return func
        return decor
    
    @setdoc('Here I am.')
    def load_this(dt):
        pass
    

    or just add docs after defining a function

    docmessage = 'Here I am.'
    def load_this(dt):
        pass
    load_this.__doc__ = docmessage