我可以在python3中格式化docstring

问题描述 投票:4回答:2

我正在尝试创建一个将接受替换字段的docstring,如下所示

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

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

但是当我在翻译中运行help(run_tests)时,我没有得到文档字符串。如果我删除{}和.format(),docstring将按预期返回。

我希望看到输出类似于:

Help on function run_tests in module myfile:

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

    usage:  myfile.py --tests

有没有办法在python3中执行此操作?

python-3.x docstring
2个回答
3
投票

您必须在函数声明后编辑函数qazxsw poi属性

__doc__

或者为docstring做一个装饰器

def run_tests(args):
    pass

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

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

0
投票

基于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 我已经定制了以下装饰器:

Python docstrings templated
© www.soinside.com 2019 - 2024. All rights reserved.