我可以在python3中格式化docstring

时间:2015-08-22 03:47:02

标签: python-3.x docstring

我正在尝试制作一个接受替换字段的文档字符串,如下所示

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

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

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

我希望看到输出类似于:

Help on function run_tests in module myfile:

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

    usage:  myfile.py --tests

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

2 个答案:

答案 0 :(得分:2)

在功能声明之后,您必须编辑函数__doc__属性

def run_tests(args):
    pass

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

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

或制作装饰器

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

答案 1 :(得分:0)

基于Python docstrings templated我已经定制了以下装饰器:

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