Python的docstring
前提
因为在查阅模型文档时看到了这样的函数,”add_end_docstrings“和”add_start_docstrings_to_model_forward“,因此想搞清楚这两个函数的作用,
同时参考此篇博客 参考
其中两个函数的源码如下:
def add_start_docstrings(*docstr):
def docstring_decorator(fn):
fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
return fn
return docstring_decorator
其实代码非常简单,就是在__doc__内加一段文本,返回值是一个内部函数。内函数传递的fn应该是一个类,因为类中才有__doc__。
def add_start_docstrings_to_model_forward(*docstr):
def docstring_decorator(fn):
docstring = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
class_name = f"[`{fn.__qualname__.split('.')[0]}`]"
intro = f" The {class_name} forward method, overrides the `__call__` special method."
note = r"""
<Tip>
Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
</Tip>
"""
fn.__doc__ = intro + note + docstring
return fn
return docstring_decorator
其中:__qualname__查阅文档,这是一个显示从模块的全局作用域到该模块中定义的某个类、函数或方法的“路径”,可以理解为 “pwd” 。所以这里的意思就是取fn这个类最原始的那个类出来。qualified name
所以这两个函数就是在类的__doc__属性上加入一段说明,仅此而已。下面分析一下我遇到的代码:
@add_start_docstrings("""T5 Model with a `language modeling` head on top.""", T5_START_DOCSTRING)
class T5ForConditionalGeneration(T5PreTrainedModel):
_keys_to_ignore_on_load_missing = [
r"encoder.embed_tokens.weight",
r"decoder.embed_tokens.weight",
r"lm_head.weight",
]
#... 下略
下面是自己的一些见解与分析:
首先第一行 @add_start_docstrings(“”“T5 Model with a language modeling
head on top.”“”, T5_START_DOCSTRING) 是装饰器,返回的是 docstring_decorator这个函数,关于装饰器可详见另一篇博客。这里简略写一下,其实等价于:
newFunc = add_start_docstrings("""T5 Model with a `language modeling` head on top.""", T5_START_DOCSTRING) #用一个新变量接受add_start_docstrings 返回的函数
newFunc(T5ForConditionalGeneration) #相当于内函数def docstring_decorator(fn)
#这就是装饰器的作用
这个装饰器加在了类 T5ForConditionalGeneration 上,因此就是在这个类的__doc__上添加了一段描述。