Use a variable to define multiple functions docstring

Viewed 641

I have several functions (a, b and c), I want them to use the same docstring. So my plan was to conserve lines by only writing the docstring once and save it to a variable DOCSTRING. Then I place it under the function declaration. I hadn't found anything in PEP 257 that addresses my problem...

DOCSTRING = '''
This is a docstring
for functions:
a,
b,
c'''

def a(x, y):
    DOCSTRING
    # do stuff with x and y

def b(x, y):
    DOCSTRING
    # do other stuffs with x and y

def c(x, y):
    DOCSTRING
    # do some more stuffs with x and y

help(a), help(b), help(c)

I actually thought it might work...but I was wrong, I got this:

Help on function a in module __main__:

a(x, y)

Help on function b in module __main__:

b(x, y)

Help on function c in module __main__:

c(x, y)

It was not at all useful.


I made my second attempt, by changing the special __doc__ attribute of the function to my docstring DOCSTRING:

DOCSTRING = '''
This is a docstring
for functions:
a,
b,
c'''

def a(x, y):
    a.__doc__ = DOCSTRING # also tried just __doc__ = DOCSTRING, both didn't work
    # do stuff with x and y

def b(x, y):
    b.__doc__ = DOCSTRING # also tried just __doc__ = DOCSTRING, both didn't work
    # do other stuffs with x and y

def c(x, y):
    c.__doc__ = DOCSTRING # also tried just __doc__ = DOCSTRING, both didn't work
    # do some more stuffs with x and y

help(a), help(b), help(c)

And the both method got the same output as the previous attempt...


What works currently is the good'ole copy-and-paste method:

def a(x, y):
    '''
    This is a docstring
    for functions:
    a,
    b,
    c'''

    # do stuff with x and y

def b(x, y):
    '''
    This is a docstring
    for functions:
    a,
    b,
    c'''

    # do other stuffs with x and y

def c(x, y):
    '''
    This is a docstring
    for functions:
    a,
    b,
    c'''

    # do some more stuffs with x and y

help(a), help(b), help(c)

And of course, it produces my desired output:

Help on function a in module __main__:

a(x, y)
    This is a docstring
    for functions:
    a,
    b,
    c

Help on function b in module __main__:

b(x, y)
    This is a docstring
    for functions:
    a,
    b,
    c

Help on function c in module __main__:

c(x, y)
    This is a docstring
    for functions:
    a,
    b,
    c

As you can see, but this way will force me to having to waste multiple lines writing the same thing...


So now, my question is, how can I get the same result as if I copied the docstring to every single function, without having to copy it to every single function?

1 Answers
Related