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

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.

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.

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"""

Correct way of commenting on commands in python [duplicate]

This question already has answers here:
Python comments: # vs. strings
(3 answers)
Closed 9 years ago.
I know two ways of leaving comments in python. One is using """ and the other is using #. I know that the first can be used to return a functions help as a benefit. But when should I use one and when the other? And also how do I have to leave comments? Do I have to press tab and arrange the first line of comment with the the command beneath it? Or do I have to start from the beginning of the line?
No, there is only one way of commenting, using #:
A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line.
Triple quoting, """, creates a string object, which happens to be used as the docstring when it is the first line of a function, module or a a class. Triple quoting is useful in many other places too, but should not be confused with commenting. You can use a triple quoted string like any other string literal, with the specific benefit that you can use actual newlines in your source code instead of having to use \n escape characters.
Although it can be used to disable a block of code by turning it into a multi-line string instead, you really should not do this. Use proper source code control and simply delete the block, or use an editor that lets you comment out whole blocks by inserting # for you instead.
For actual comments, use #. The Python style guide (PEP 8) has some things to say about when and how to use commenting; it has this to say about indentation:
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).

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
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.

Categories

Resources