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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With