我可以在 python3 中格式化文档字符串吗
Can I format the docstring in python3
我正在尝试制作一个接受替换字段的文档字符串,如下所示
def run_tests(args):
"""run tests on methods in {0}
usage: {0} --tests
""".format(__file__)
pass
但是当我在解释器中 运行 help(run_tests)
时,我没有得到文档字符串。如果我按预期删除 {} 和 .format() 文档字符串 returns。
我希望看到类似这样的输出:
Help on function run_tests in module myfile:
run_tests(args)
runs tests on methods in myfile.py
usage: myfile.py --tests
在 python3 中有没有办法做到这一点?
我在的基础上定制了如下装饰器:
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
您必须在函数声明后编辑函数 __doc__
属性
def run_tests(args):
pass
run_tests.__doc__ = """\
run tests on methods in {0}
usage: {0} --tests
""".format(__file__)
或者为 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
我正在尝试制作一个接受替换字段的文档字符串,如下所示
def run_tests(args):
"""run tests on methods in {0}
usage: {0} --tests
""".format(__file__)
pass
但是当我在解释器中 运行 help(run_tests)
时,我没有得到文档字符串。如果我按预期删除 {} 和 .format() 文档字符串 returns。
我希望看到类似这样的输出:
Help on function run_tests in module myfile:
run_tests(args)
runs tests on methods in myfile.py
usage: myfile.py --tests
在 python3 中有没有办法做到这一点?
我在
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
您必须在函数声明后编辑函数 __doc__
属性
def run_tests(args):
pass
run_tests.__doc__ = """\
run tests on methods in {0}
usage: {0} --tests
""".format(__file__)
或者为 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