MarkNS
MarkNS

Reputation: 4021

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

Upvotes: 1

Views: 1266

Answers (2)

Cong Ma
Cong Ma

Reputation: 11302

Instead of programmatically generating the docstring (rather unpythonic in my opinion), what stops you from just define a function load like

def load(dt, filter_):
    ... ...

and write a single documentation for it? I really fail to see the need for 3 separate functions.

Even if you some how do, you can always create them, after defining the above function load, by partialing them.


Edit: After the comment by OP, I think you can simply write the doc for dt once in one of the functions (presumably the most basic, "prototype" one) and in other function simply say

"See the documentation of ___ for details about dt".

Yes, you can splice docstrings smartly like

some_function.__doc__ = some_function.__doc__ + "doc for dt"

or more smartly than that by writing your own documentation-generating metaclass generator factor factory framework, but why? ;)

Upvotes: 1

Speaking Code
Speaking Code

Reputation: 141

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

Upvotes: 2

Related Questions