如何在python代码中包装和对齐注释

LWZ*_*LWZ 3 python emacs comments alignment

我试图让我的python代码看起来更具可读性.我阅读了风格指南,但我不知道如何得到这样的东西

x = foo(x);  # compute the value of the next prime number
             # that is larger than x  (foo is a really bad 
             # choice for this function's name) 
Run Code Online (Sandbox Code Playgroud)

或这个

x = x + 1                 # Compensate for border
some other code           # some other comment
Run Code Online (Sandbox Code Playgroud)

你如何包装评论并将它们对齐?你不只是输入一堆space,是吗?如果我编辑了代码,我是否必须手动重新排列注释?

我正在使用emacs作为我的编辑器.

aba*_*ert 9

我认为你根本不想要这个.Lattyware已经解释了第二种情况,但让我们来看看第一种情况:

x = foo(x);  # compute the value of the next prime number
             # that is larger than x  (foo is a really bad 
             # choice for this function's name) 
Run Code Online (Sandbox Code Playgroud)

太长而无法嵌入的注释可以转换为代码上方的块注释,如下所示:

# compute the value of the next prime number that is larger than
# x (foo is a really bad choice for this function's name)
x = foo(x);
Run Code Online (Sandbox Code Playgroud)

这似乎比右对齐的评论更具可读性.它还为您提供更多空间.使用emacs肯定更容易(只需键入整个内容和meta-Q).并引用PEP 8中的内联评论:

谨慎使用内联评论.

内联注释是与语句在同一行上的注释.

这是内联注释的样式指南的开始,它强烈地暗示如果你想要写的数量超过你可以放在同一行上,你应该使用块注释.

另外,在我们谈论PEP 8时:

  • "评论应该是完整的句子." 您的第一条评论需要期间.(是的,它也说"如果评论很短,最后的句号可以省略",但你有一个3行2句的评论,所以这里不适用.)
  • "如果评论是短语或句子,则其第一个词应该大写".所以,大写"Compute"(但不是"foo",因为那是一个标识符).
  • 不要添加函数名称不好的注释,只需重命名该函数即可.
  • 摆脱那个分号.

所以:

# Compute the value of the next prime number that is larger than x.
x = next_larger_prime(x)
Run Code Online (Sandbox Code Playgroud)

但是一旦你这样做了,你甚至不需要评论.

事实上,这很常见.当您发现自己想知道如何打破评论的样式指南时,您可能应该通过询问如何重新组织代码以使其不需要所有这些注释.这并不总是可能,但通常值得至少尝试.