Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I format the docstring in python3

I am trying to make a docstring that will accept replacement fields as follows

def run_tests(args):
    """run tests on methods in {0}

    usage: {0} --tests
    """.format(__file__)
    pass

but when I run help(run_tests) in the interpreter, I do not get the docstring. If I remove {} and .format() the docstring returns as expected.

I would like to see the output something like:

Help on function run_tests in module myfile:

run_tests(args)
    runs tests on methods in myfile.py

    usage:  myfile.py --tests

Is there a way to do this in python3?

like image 844
posop Avatar asked Aug 22 '15 03:08

posop


2 Answers

You have to edit the function __doc__ attribute after the fuction declaration

def run_tests(args):
    pass

run_tests.__doc__ = """\
    run tests on methods in {0}

    usage: {0} --tests
    """.format(__file__)

or make a decorator for doctring

def doc(arg):
    """Docstring decorator.

    arg:    Docstring text or object.
    """
    import inspect

    def decorator(func):
        if type(arg) is str:
            func.__doc__ = arg
        elif inspect.isclass(arg):
            func.__doc__ = arg.__doc__
        else:
            func.__doc__ = None

        return func
    return decorator

@doc(
    f"""run tests on methods in {__file__}

    usage: {__file__} --tests
    """
)
def run_tests(args):
    pass
like image 123
Corleo Avatar answered Nov 13 '22 00:11

Corleo


Based on Python docstrings templated I have tailored the following decorator:

def _formatDostring(*args, **kwargs):
    def decorator(o):
        o.__doc__ = o.__doc__.format(*args, **kwargs)
        return o

    return decorator

@_formatDostring(__file__=__file__)
def run_tests(args):
    """run tests on methods in {__file__}

    usage: {__file__} --tests
    """
    pass
like image 26
abukaj Avatar answered Nov 12 '22 23:11

abukaj