深度学习代码笔记1-Python的docstring

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__上添加了一段描述。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值