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.
Related
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.
Is the usage of escaped characters such as \t allowed by PEP8 in something like print statements?
Is there a more idiomatic way to left indent some of the printout without importing non standard libraries?
Yeah that's fine, it is a fundamental ASCII character - PEP would not deny its use as it may be fundamental to your end result (say an API needed tabs or something) - PEP is all about styling your source code, I wouldn't consider a character in a string to be something that can be decreed by a style guide (PEP8).
Though there is nothing wrong with using \t, you might want to use the textwrap module to allow your indented text to be displayed more naturally in your source code. As an alternative to msg = '\teggs\tmilk\tbread', you can write
import textwrap
def show_list():
msg = """\
eggs
milk
bread"""
print(textwrap.indent(textwrap.dedent(msg), "\t"))
Then show_list() produces the output
eggs
milk
bread
When you indent the definition of msg, the whitespace is part of the literal. dedent removes the common leading whitespace from each line of the string. The indent method then indents each line with, specifically, a tab character.
There is nothing wrong using the tabulator character in a string, at all. See e.g. the Wikipedia link for some common usages. You may be confused by this PEP-8 info:
Use 4 spaces per indentation level.
This is similar to Joe Iddon's answer. It has to be clear that writing a text (not code, of course) is something different than writing code. Texts and their usages are very inhomogeneous. So setting rules how to format your text does not make any sense (if text is not code).
But you also asked "Is there a more idiomatic way to left indent some of the printout without importing non standard libraries?"
Since Python3.6 You can use formatted string literals to get additional spaces (indentation) in your strings you want to print. (If you're using Python3.5 and lower, you can use the str.format instead, for example.)
The usage is like this:
>>> text = "Hello World"
>>> print(f"\t{text}")
Hello World
This is just a toy example, of course. F-Strings become more useful with more complex strings. If you don't have such complex strings, you can consider also using the arguments of print() statement like this, for example:
>>> print("Foo", "Bar", "Foo", "Bar", sep="\t\t") # doubled "\t" only for better displaying
Foo Bar Foo Bar
But often it is simply quite enough to include the tab character in your string, e.g.: "Hello World!\tHow are you doing?\tThat's it.". As already said, don't do that with code (PEP-8), but in texts it is fine.
If you want to use a module for that (it is a built-in module), I recommend using textwrap. See chepner's answer for more information how to use that.
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"""
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.
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.