IndentationError from comment in python

可紊 提交于 2021-02-07 02:40:13

问题


How come python reacts to indentations of a comment?

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

works, but:

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

doesn't work, throwing an IndentationError.

Seems weird to me since comments shouldn't be nothing more then comments. And by the way, this works:

def foo():
# Another random comment
    return True

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11860064/indentationerror-from-comment-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!