python - 文档字符串应该放在装饰器之前还是之后?

比较以下内容。

示例 1:装饰器之前的文档字符串。

@app.route("/")
"""
summary
"""
def hello() -> str:
    return "Hello World"

对比示例 2:装饰器之后的文档字符串:

"""
summary
"""
@app.route("/")
def hello() -> str:
    return "Hello World"

最佳答案

文档字符串应该放在哪里?

文档字符串应该放在函数内部,函数头之后的第一件事:

@app.route("/")
def hello() -> str:
    """
    summary
    """
    return "Hello World"

规范本身 ( PEP 257 ) 明确表示:

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition.

为什么?

这很重要,因为文档字符串不仅仅是一种约定。

如果你把它们放在正确的位置,你可以看到带有help() function的函数文档。 (甚至可能还有其他工具):

>>> @app.route("/")
... def hello() -> str:
...     """
...     summary
...     """
...     return "Hello World"
... 
>>> help(hello)
Help on function hello in module __main__:

hello() -> str
    summary

发生这种情况是因为,如果字符串文字是函数声明中的第一件事,解释器会将其设置为函数的 __doc__ 属性:

>>> hello.__doc__
'\n    summary\n    '

help() 基本上只是以良好的格式显示 __doc__ 属性的值。

https://stackoverflow.com/questions/71242711/

相关文章:

python - 极地 : switching between dtypes within a Da

python - 我们如何提取数据框中具有顺序值的行?

docker - 如何通过 SSH 进入 colima 实例

arrays - Perl 中是否有任何函数可以移动数组元素而不删除它们?

python - 理解 python 的 len() 时间复杂度

c++ - 键入 “$” 命令不会跳转到行尾 [光标设置为 “|”(条形/管道)而不是 block

python - 如何在不完全用 Python 重写的情况下在函数内部添加、删除和编辑某些行?

python - 两个日期时间之间的 15 分钟间隔数

javascript - 使用 useState 从数组中删除最后一项

swift - 如何快速制作圆形或填充和圆形进度 View (使用 CAShapeLayers)