IndentationError from comment in python

前端 未结 2 1807
走了就别回头了
走了就别回头了 2021-02-15 18:12

How come python reacts to indentations of a comment?

def foo():
    \"\"\"
    Random comment
    \"\"\"
    return True

works, but:

         


        
相关标签:
2条回答
  • 2021-02-15 18:32

    The triple-quoted string is not a comment, it is a string literal. It's not assigned or used in any way by your code, but it's still a regular string and has to fit the syntax of Python. (In this case it happens to be the docstring, but that has nothing to do with whether indentation matters for it or not.)

    # is the way to get comments.

    0 讨论(0)
  • 2021-02-15 18:39

    The tripple-quoted string is not a comment; it is the docstring of the method. You can access it with foo.__doc__ later, for example, or have it formatted for you with help(foo). Tripple-quoting (""" or ''') is a python-specific method of specifying a string literal where newlines do not need to be escaped.

    As such, it is part of the body of the function, and thus needs to be indented to match. In fact, any string appearing as the first statement of a function is treated as a docstring, single quoting would work too. The same trick works for classes and modules too.

    A lot of tools can make use of this documentation string; you can embed doctest tests in this information, for example. See PEP 257 for conventions on formatting this string.

    Comments on the other hand, are always denoted by a # (where not part of a string literal) and are ignored up to the end of a line. If all the line contains is a comment, the whole line is thus ignored, as would a line with only whitespace. See the documentation on comments.

    0 讨论(0)
提交回复
热议问题