Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndentationError from comment in python

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
like image 549
SlimJim Avatar asked Aug 08 '12 07:08

SlimJim


People also ask

What is IndentationError in Python?

An indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The indentation error can occur when the spaces or tabs are not placed properly. There will not be an issue if the interpreter does not find any issues with the spaces or tabs.

How do you remove indentation in Python?

If you're using IDLE, you can use Ctrl+] to indent and Ctrl+[ to unindent.


2 Answers

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.

like image 166
Martijn Pieters Avatar answered Sep 28 '22 07:09

Martijn Pieters


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.

like image 24
BrenBarn Avatar answered Sep 28 '22 06:09

BrenBarn