注释行超过 79 个字符

More than 79 chars at line with comment

我应该怎么办,例如这一行: full_path = "https://www.google.cz/search?q=" + website_keywords # google link url Flake8 报告我,行中的字符数超过 79 个最大值。长度。那么当 PEP 8 说内联注释应该与特定语句在同一行时,我应该如何处理注释。

在行上方添加这样的评论通常没问题:

# google link url
full_path = "https://www.google.cz/search?q=" + website_keywords

顺便说一下,截至撰写本文时,PEP 8 表示评论的行数限制仅为 72。

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.

...

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters (effectively increasing the maximum length to 99 characters), provided that comments and docstrings are still wrapped at 72 characters.

尚不清楚这是否适用于内嵌注释,因为它们不是“长文本块”,但 PEP 8 还说,

Inline comments are unnecessary and in fact distracting if they state the obvious.

您可以考虑完全删除该评论。考虑到字符串中包含“google”,它是 Google URL 的事实是显而易见的。


在一种情况下,评论确实必须与其所评论的内容在同一行--PEP-484 type comments。在这种情况下,您使用括号:

full_path = (
    "https://www.google.cz/search?q=" + website_keywords
)  # type: str

相信一个更pythonic的方法可能如下:

from urllib.parse import urlencode
def format_url(website_keywords):
    """Return google link url."""
    parameters = urlencode({"q": website_keywords}, True)
    root_url = "https://www.google.cz/search"
    return "%s/%s" % (root_url, parameters)