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

Viewed 3162

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?

3 Answers

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

Fruthermore, 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:

enter image description here

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.

Related