加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:29:37 所属栏目:Python 来源:网络整理
导读:我试图让我的 python代码看起来更具可读性.我读了 style guide,但我不知道如何得到这样的东西 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) 或这个 x = x +
我试图让我的 python代码看起来更具可读性.我读了 style guide,但我不知道如何得到这样的东西

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)

或这个

x = x + 1                 # Compensate for border
some other code           # some other comment

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

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

解决方法

我认为你根本不想要这个. 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)

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

# 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);

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

Use inline comments sparingly.

An inline comment is a comment on the same line as a statement.

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

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

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

所以:

# Compute the value of the next prime number that is larger than x.
x = next_larger_prime(x)

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读