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

标签 python decorator pep8 docstring

比较以下内容。

示例 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__ 属性的值。

关于python - 文档字符串应该放在装饰器之前还是之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71242711/

相关文章:

.net - WPF 装饰器类有用吗?

python - PEP 8 规则的现状?

python - PEP8 和 PyQt,如何协调函数大小写?

python - Flask Limiter - 对一个端点使用多个 key_func

python - Marshmallow 转储缺少 1 个必需的位置参数 : 'obj'

python - 如何使用python引用可调用装饰器对象中的对象实例?

python - 你能在运行时更改 python 描述符的 __get__ 方法吗?

python - Django - 在模板中显示数据

python - 如何在 tensorflow 中提取层或 ValueError : Shape (? , 4096) 必须具有排名 1

python - 在 Eclipse 中为远程系统资源管理器启用 pep8