为什么动态格式化文档字符串不起作用?在函数定义时执行此操作是否有可接受的解决方法?

>>> DEFAULT_BAR = "moe's tavern"
>>> def foo(bar=DEFAULT_BAR):
...     """
...     hello this is the docstring
...
...     Args:
...       bar (str)    the bar argument (default: {})
...     """.format(DEFAULT_BAR)
...
>>> foo.__doc__
>>> foo.__doc__ is None
True

我尝试使用 old-skool 风格的 %s 格式,但也没有用。

最佳答案

尝试这样的事情(向@user2357112 提出建议):

#!python3

def FORMAT_DOC(f):
    """Decorator to format docstring of a function. Supplies
    `defaults` dictionary, positional values, and argname:value
    pairs to format - use {defaults[a]} or {a} or {0} to access
    the 0th default value, etc.
    """
    defaults = f.__defaults__
    docs = f.__doc__

    if docs and defaults:
        nargs = f.__code__.co_argcount
        argnames = f.__code__.co_varnames[nargs-len(defaults):nargs]
        argdefaults = dict(zip(argnames, defaults))
        f.__doc__ = docs.format(defaults=argdefaults, *defaults, **argdefaults)

    return f

@FORMAT_DOC
def f(a):
    pass

@FORMAT_DOC
def f(a,b,c=1,d=2):
    """Docstring

    By default, c = {} and d = {}
    """
    v=a+c
    w=b+d
    x=w/v
    return x+1

@FORMAT_DOC
def f(a=0, b="foo", c="bar"):
    """Docstring: a={0}, b={defaults[b]}, c={c}"""
    pass

关于Python 文档字符串模板化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36705130/

10-08 22:15