IndentationError from comment in python - 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

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.

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.

Related

In Python 3.5, how are triple quotes (""") considered comments by the IDE?

My CS teacher told me that """ triple quotations are used as comments, yet I learned it as strings with line-breaks and indentations. This got me thinking about - does python completely triple quote lines outside of relevant statements?
"""is this completely ignored like a comment"""
-or, is the computer actually considering this?
Triple quoted strings are used as comment by many developers but it is actually not a comment, it is similar to regular strings in python but it allows the string to be in multi-line. You will find no official reference for triple quoted strings to be a comment.
In python, there is only one type of comment that starts with hash # and can contain only a single line of text.
According to PEP 257, it can however be used as a docstring, which is again not really a comment.
def foo():
"""
Developer friendly text for describing the purpose of function
Some test cases used by different unit testing libraries
"""
<body of the function>
You can just assign them to a variable as you do with single quoted strings:
x = """a multi-line text
enclosed by
triple quotes
"""
Furthermore, if you try in repl, triple quoted strings get printed, had it really been a comment, should it have been printed?:
>>> #comment
>>> """triple quoted"""
'triple quoted'
As someone else already pointed out, they are indeed strings and not comments in Python. I just wanted to add a little more context about your question of "is the computer actually considering it?"
The answer is yes, since it isn't a comment. Take the below code for example:
def my_func():
"""
Some string
"""
print("Hello World!")
my_func()
Trying to run this will actually produce a syntax error because of the indentation.
So as far as I know, triple quotes can be used for both purposes but # is the standard for commenting.
According to this website, what I can understand is that ''' This '''
can be used as a comment and because they are handled as docstrings technically (not tested) ' This ' can also act as a comment depending on where put it. However, even though single and triple quotes can be used as comments, it does not mean that they are comments. For example, # comments are compeletely ignored by the interpreter whereas ''' comments might be loaded into memory (just a probable guess, not confirmed). But from what I can tell, they aren't handled as comments as shown below:
So they are not but they can be used as comments. Generally speaking, use #.
EDIT:
As #BTables pointed out, you will get an indentation error if you don't indent them correctly. So they are indeed handled as strings.

Python multiline comment doesn't work in terminal

Everywhere I look tells me that a multiline comment can be created as:
'''
This is a multiline
comment.
'''
(see eg this answer, and many more).
However, when I execute this in a python or ipython terminal I see my multiline 'comment' printed.
>>> '''
... This is a multiline
... comment.
... '''
'\nThis is a multiline\ncomment.\n'
>>>
This was not the behaviour I expected. I was led to believe the above code was equivalent to using hashes to denote comments:
>>> # This is also a multiline
... # comment.
...
>>>
which, as I expected, doesn't print anything at all.
So what gives here? Everywhere is telling me I can create multiline comments with the ''' or """ syntax. But, when I'm working directly in a terminal, I don't observe this supposed behaviour.
Is the behaviour in my first example because my comment was interpreted to be a docstring and was therefore printed?
That's because it's a multi line string literal, not a multi line comment. It can be used as a multi line comment though, because, just as a comment, it doesn't "do anything", and it seems that it's ignored, just like a comment.
However, as you observed, the string literal actually evaluates to a string object with all the newline characters and stuff. Comments, on the other hand, are ignored completely and aren't evaluated to anything.
''' and """ are actually for multiline string.
# is telling the interpreter to skip the rest of the line.
You are currently running it in REPL, so ''' and """ would return a string, and it will be shown in your REPL.
If you are running it in python program, such as python [filename.py] it will not be shown, unless you use print "Hello world"
Also, the ''' and """ commonly use as multiline docstring in PEP guideline, see https://www.python.org/dev/peps/pep-0257/#id17
Triple-quoted text is considered a string in Python, not a comment.
Try '''I am a triple-quoted string'''.split(), split() will work just fine since the object is a string.

Difference between comments in Python, # and """

Starting to program in Python, I see some scripts with comments using # and """ comments """.
What is the difference between these two ways to comment?
The best thing would be to read PEP 8 -- Style Guide for Python Code, but since it is longish, here
is a three-liner:
Comments start with # and are not part of the code.
String (delimited by """ """) is actually called a docstring and is used on special places for defined purposes (briefly: the first thing in a module or function describing the module or function) and is actually accessible in the code (so it is a part of the program; it is not a comment).
Triple quotes is a way to create a multi-line string and or comment:
"""
Descriptive text here
"""
Without assigning to a variable is a none operation that some versions of Python will completely ignore.
PEP 8 suggests when to use block comment/strings, and I personally follow a format like this:
Example Google Style Python Docstrings
The string at the start of a module, class or function is a docstring:
PEP 257 -- Docstring Conventions
that can be accessed with some_obj.__doc__ and is used in help(...). Whether you use "Returns 42" or """Returns 42""" is a matter of style, and using the latter one is more common, even for single-line documentation.
A # comment is just that, a comment. It cannot be accessed at runtime.
The # means the whole line is used for a comment while whatever is in between the two """ quotes is used as comments so you can write comments on multiple lines.
As the user in a previous answer stated, the triple quotes are used to comment multiple lines of code while the # only comments one line.
Look out though, because you can use the triple quotes for docstrings and such.

Why does values enclosed in multi line comment work in python

Basically I have a print statement with a value enclosed in a multi line comment block. I am expecting it to be an error but I found out that it actually prints the text enclosed. I am curious as to why it does that.
print '''Test String'''
Python has no multi-line comment syntax. You got confused with one of the Python string literal forms instead.
'''....''' creates a string, just like '...' does. There is a """....""" form as well. The difference is that newlines are permitted in the triple-quoted without requiring escaping:
multi_line_string = '''This is the first line.
But multiple lines are included.
And each newline is included in the value.
'''
You probably thought of these as comments because Python developers prefer this form when creating the documentation string. Python gives special meaning to a string literal used as the first statement in a module, class or function, storing the contents in the object __doc__ attribute.
You don't have to use triple-quoted strings for that, single quotes work too:
>>> def foo():
... 'The foo function'
... return 'bar'
...
>>> foo.__doc__
'The foo function'
The Python style guide recommends you use triple-quoting, always, using double quotes, like this:
def recommended():
"""This is a documentation string.
It follows the style guide by using triple quotes.
"""
See the PEP 257: Docstring Conventions for more information.
Lines enclosed with three quotes are not comments, they are strings. However, python can take them as a comment, the same way this is also a comment
"foo"
#bar
"""foobar"""

Why does python use unconventional triple-quotation marks for comments?

Why didn't python just use the traditional style of comments like C/C++/Java uses:
/**
* Comment lines
* More comment lines
*/
// line comments
// line comments
//
Is there a specific reason for this or is it just arbitrary?
Python doesn't use triple quotation marks for comments. Comments use the hash (a.k.a. pound) character:
# this is a comment
The triple quote thing is a doc string, and, unlike a comment, is actually available as a real string to the program:
>>> def bla():
... """Print the answer"""
... print 42
...
>>> bla.__doc__
'Print the answer'
>>> help(bla)
Help on function bla in module __main__:
bla()
Print the answer
It's not strictly required to use triple quotes, as long as it's a string. Using """ is just a convention (and has the advantage of being multiline).
A number of the answers got many of the points, but don't give the complete view of how things work. To summarize...
# comment is how Python does actual comments (similar to bash, and some other languages). Python only has "to the end of the line" comments, it has no explicit multi-line comment wrapper (as opposed to javascript's /* .. */). Most Python IDEs let you select-and-comment a block at a time, this is how many people handle that situation.
Then there are normal single-line python strings: They can use ' or " quotation marks (eg 'foo' "bar"). The main limitation with these is that they don't wrap across multiple lines. That's what multiline-strings are for: These are strings surrounded by triple single or double quotes (''' or """) and are terminated only when a matching unescaped terminator is found. They can go on for as many lines as needed, and include all intervening whitespace.
Either of these two string types define a completely normal string object. They can be assigned a variable name, have operators applied to them, etc. Once parsed, there are no differences between any of the formats. However, there are two special cases based on where the string is and how it's used...
First, if a string just written down, with no additional operations applied, and not assigned to a variable, what happens to it? When the code executes, the bare string is basically discarded. So people have found it convenient to comment out large bits of python code using multi-line strings (providing you escape any internal multi-line strings). This isn't that common, or semantically correct, but it is allowed.
The second use is that any such bare strings which follow immediately after a def Foo(), class Foo(), or the start of a module, are treated as string containing documentation for that object, and stored in the __doc__ attribute of the object. This is the most common case where strings can seem like they are a "comment". The difference is that they are performing an active role as part of the parsed code, being stored in __doc__... and unlike a comment, they can be read at runtime.
Triple-quotes aren't comments. They're string literals that span multiple lines and include those line breaks in the resulting string. This allows you to use
somestr = """This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is\
significant."""
instead of
somestr = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
Most scripting languages use # as a comment marker so to skip automatically the shebang (#!) which specifies to the program loader the interpreter to run (like in #!/bin/bash). Alternatively, the interpreter could be instructed to automatically skip the first line, but it's way more convenient just to define # as comment marker and that's it, so it's skipped as a consequence.
Guido - the creator of Python, actually weighs in on the topic here:
https://twitter.com/gvanrossum/status/112670605505077248?lang=en
In summary - for multiline comments, just use triple quotes. For academic purposes - yes it technically is a string, but it gets ignored because it is never used or assigned to a variable.

Categories

Resources