文档字符串 - 一行与多行

发布于 2025-01-08 03:01:09 字数 764 浏览 0 评论 0原文

我正在向我编写的包中添加一些(epydoc)文档,并且我遇到了很多时候我都会重复自己很多次。

def script_running(self, script):
    """Return if script is running

    @param script: Script to check whether running

    @return: B{True} if script is running, B{False} otherwise
    @rtype: C{bool}
    """

PEP257 说:

单行话适用于非常明显的情况。

还有

函数或方法的文档字符串应总结其行为并记录其参数、返回值、副作用、引发的异常以及调用时间的限制(全部如果适用)。


是否有关于何时在单行(描述)和完整参数/返回字段之间划清界限的一般准则或标准实践?

或者,在生成文档时,我应该包含每个函数的每个适用字段,无论它看起来有多么重复?

额外问题:从语法上来说,描述 script 参数的最佳方式是什么?

I'm adding some (epydoc) documentation to a package I've written, and I'm coming across a lot of instances where I'm repeating myself a multitude of times.

def script_running(self, script):
    """Return if script is running

    @param script: Script to check whether running

    @return: B{True} if script is running, B{False} otherwise
    @rtype: C{bool}
    """

PEP257 says that:

One-liners are for really obvious cases.

and also

The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable).


Is there a general guideline or standard practice for when to draw the line between a one-liner (description) and full param/return fields?

Or when generating documentation should I include every applicable field for each function, regardless of how repetitive it seems?

Bonus question: Syntactically, what's the best way to describe the script param?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

[浮城] 2025-01-15 03:01:09

您正在寻找的一般指南就在您引用的 PEP257 中,也许您只需要看看它的实际效果。

您的函数非常适合单行文档字符串(“非常明显的情况”):

def script_running(self, script):
    """Check if the script is running."""

通常,如果您说某个函数正在检查某些内容,则意味着它将返回 True 或 False,但如果您愿意,您可以更具体:

def script_running(self, script):
    """Return True if the script is running, False otherwise."""

再次全部在一行中。

我可能还会更改函数的名称,因为不需要强调函数的名称(脚本)的工作原理。函数名称应该是甜美、简短且有意义的,能够说明函数的功能。也许我会同意:

def check_running(self, script):
    """Return True if the script is running, False otherwise."""

有时函数名称想象对所有编码感到厌倦,但无论如何你都应该尽力而为。

对于多行示例,让我从 google 借用文档字符串指南

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """

这可能是“总结其行为并记录其参数、返回值、副作用、引发的异常以及何时调用它的限制(所有如果适用)”的一种方法。

您可能还有兴趣查看pypi 项目示例它应该用 Sphinx 进行记录。

我的 2 美分:指南旨在让您了解应该做什么和不应该做什么,但它们并不是您必须盲目遵循的严格规则。所以最后选择你觉得更好的。


我想澄清另一个答案中关于使用文档字符串达到最大行长度的内容。

PEP8 告诉您“将所有行限制为最多 79 行”个字符”,即使最后每个人都做了 80 个字符。

这是 80 个字符:

--------------------------------------------------------------------------------

这可能是一种边缘情况,您真正需要的只是一个长一点的句子:

def my_long_doc_function(arg1, arg2):
    """This docstring is long, it's a little looonger than the 80 characters
    limit.
    
    """

就像单行文档字符串,这意味着对于非常明显的情况,但在你的编辑器上(有 80 个字符的限制)是多行的。

The general guideline you are looking for is right in PEP257 in what you quoted, maybe you just need to see it in action.

Your function is a good candidate for a one-line docstring ("really obvious cases"):

def script_running(self, script):
    """Check if the script is running."""

Usually if you say that a function is checking something it means that it's going to return True or False, but if you like you could be more specific:

def script_running(self, script):
    """Return True if the script is running, False otherwise."""

Once again all in one line.

I would probably also change the name of your function, because there's no need to emphasize on what the function works in its name (a script). A function name should be something sweet, short and meaningful about what the function does. Probably I'd go with:

def check_running(self, script):
    """Return True if the script is running, False otherwise."""

Sometimes the function-name-imagination is tired by all the coding, but you should try anyway to do your best.

For a multiline example, let me borrow a docstring from the google guidelines:

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """

This could be one way to "summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable)".

You might also be interested to look at this example of pypi project that it's meant to be documented with Sphinx.

My 2 cents: Guidelines are meant to give you an idea about what you should and shouldn't do, but they are not strict rules that you have to blindly follow. So at the end choose what you feel to be better.


I would like to clear something that is been said in another answer about hitting the Maximum Line Length with a docstring.

PEP8 tells you to "Limit all lines to a maximum of 79 characters" even though at the end everyone does 80.

This are 80 characters:

--------------------------------------------------------------------------------

And this may be an edge case where a little long one sentence is all you really need:

def my_long_doc_function(arg1, arg2):
    """This docstring is long, it's a little looonger than the 80 characters
    limit.
    
    """

Is like a one-line docstring, meaning that is for really obvious cases, but on your editor (with the 80 character limit) is on multiple lines.

番薯 2025-01-15 03:01:09

我认为在为文档字符串添加扩展语法(即 epydoc/sphinx 标记)时,可能总会涉及一定程度的重复。

我还想说,这个问题是主观的,而不是客观的。显式比隐式更好,并且似乎更遵循 Python 的禅宗。

I think there is likely always some degree of repetition involved when adding extended syntax for docstrings, i.e. epydoc/sphinx markup.

I would also say this matter is subjective rahter than objective. Explicit is better than implicit, and would seem to follow the Zen of Python more.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文