正确使用评论

3 python comments conventions

对于 Python 代码,PEP 257提供了使用文档字符串来记录结构实体的约定:包、模块、函数、类和方法。

\n

这几乎涵盖了所有内容。Stack\xc2\xa0Overflow 有关如何注释 Python 代码的问题总是会引出使用文档字符串的答案。

\n

这在哪里留下评论?Pythonic 方法是专门使用文档字符串而不使用注释吗?或者他们有什么地方吗?

\n

Python 代码中注释的正确用法是什么?

\n

wp-*_*com 6

Doc-strings = 使用您的函数的人的信息
Inline-comments = 解释为什么代码是这样编写的。

请参阅requests 库,了解适当使用注释的项目的一个很好的示例。

何时使用文档字符串

好的文档字符串提供的信息类型与您在阅读 Python 文档时通常看到的信息类型相同。他们解释函数的作用,描述参数,如果返回某些内容,他们应该提及。文档字符串还应该提及调用该函数可能发生的任何副作用。

思考文档字符串的一种方法是考虑如果该函数在某些在线文档中显示,您希望显示的信息。像Sphinx这样的程序可以根据文档字符串自动生成文档。

何时使用注释

另一方面,注释解释了令人困惑的代码片段。他们的目的是帮助正在修复错误或以其他方式更改代码的人了解您的代码在做什么。它们应该被用来帮助解释那些仅仅通过查看它们而无法自解释的代码行。

例子

以下面的洗牌算法为例。请注意,注释的重点是解释算法如何工作,而不是每行代码的作用。我们知道如何阅读代码,但是注释中的信息对于查看代码的任何人来说都是有用的信息。另一方面,文档字符串提供了任何需要使用 shuffle 函数的人想要知道的所有信息。他们不关心算法的内部结构。他们关心 shuffle 函数的输入和输出。

def shuffle(artist_song_dict):
    """ Shuffles songs in a semi-random fashion while keeping songs by the same artist spread out, as described in
    https://labs.spotify.com/2014/02/28/how-to-shuffle-songs/
    artist_song_dict must be a dictionary where the keys equal the artist names and the values are an iterable of each artist's songs
    A list of shuffled songs is returned
    """
    lineup = {} #each song will be stored in this dictionary with a value between 0 and 1 representing the song's position in the lineup
    variation = .3
    for artist in artist_song_dict:
        songs = artist_song_dict[artist]
        random.shuffle(songs)

        # Distance between songs in the lineup, if we were to space the songs out evenly
        spread = 1/len(songs)

        # This is reffered to as the offset in the article, but I found this has a different purpose than what the article says.
        # Without this random variation, the number of songs an artists has in the lineup affects the probablity that their songs
        # will appear first (or sooner/later) in the lineup versus other artists
        artist_variation = random.uniform(0, spread-variation)

        for i, song in enumerate(songs):
            # We want to add some randomization to the lineup, but not too much, 
            # otherwise, songs by the same artists could be played twice.
            # The article recommends adding a 30% variation to each song
            song_variation = random.uniform(0, spread*variation)

            # Assign this song the next evenly spaced spot in the lineup plus our variations
            lineup[song] = i*(spread) + artist_variation + song_variation

    return sorted(lineup, key=lineup.get)
Run Code Online (Sandbox Code Playgroud)



内联评论与块评论

内嵌评论看起来像这样

x = x + 1                 # Compensate for border
Run Code Online (Sandbox Code Playgroud)

虽然块评论看起来像这样

# Compensate for border.  These comments
# often cover multiple lines.
x = x + 1
Run Code Online (Sandbox Code Playgroud)

两者都是有效的评论形式。我只是想指出有两种形式的评论。PEP 8 特别指出要谨慎使用内联注释。我相信他们正在反对不恰当地使用注释来解释每一行代码的工作原理。您经常在教程和 SO 中看到这种情况,但在实践中,您不应该注释不言自明的代码。