1413

How do I make multi-line comments? Most languages have block comment symbols like:

/*

*/
8
  • 4
    I suppose being an interpreted language, it makes sense, as in the case of sh or bash or zsh, that # is the only way to make comments. I'm guessing that it makes it easier to interpret Python scripts this way. Mar 14, 2017 at 16:29
  • 1
    I know this answer is old, but I came across it because I had the same question. The accepted answer DOES work, though I don't know enough of Python to know the intricacies of why it may not be correct (per ADTC). Jul 7, 2017 at 12:55
  • 7
    @BrandonBarney Let me explain you the issue. The accepted answer, which uses ''', actually creates a multi-line string that does nothing. Technically, that's not a comment. For example, you can write k = '''fake comment, real string'''. Then, print(k) to see what ADTC means.
    – pinyotae
    Aug 6, 2017 at 3:13
  • 3
    That makes so much more sense now. I'm used to vba where creating an unused string results in an error. I didn't realize python just ignores it. It still works for debugging and learning at least, but isn't good practice for actual development. Aug 6, 2017 at 21:20
  • In Python source code, if you break a long line, the editor automatically indents it, to show that the broken line is really part of the previous line? Is that what I should do if I break up a long line of pseudocode?
    – alpha_989
    Jan 31, 2018 at 18:41

27 Answers 27

2155

You can use triple-quoted strings. When they're not a docstring (the first thing in a class/function/module), they are ignored.

'''
This is a multiline
comment.
'''

(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)

Guido van Rossum (creator of Python) tweeted this as a "pro tip".

However, Python's style guide, PEP8, favors using consecutive single-line comments, like this:

# This is a multiline
# comment.

...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.

28
  • 31
    Hm. I put a huge multiline string in a python script test.py just to see. When I do import test, a test.pyc file is generated. Unfortunately, the pyc file is huge and contains the entire string as plain text. Am I misunderstanding something, or is this tweet incorrect?
    – unutbu
    Oct 8, 2011 at 13:18
  • 28
    @unutbu, if it was the only thing in the file, it was a docstring. Put some code before it and it'll disappear from the pyc. I edited the answer and put „module“ to the list of things that have docstrings. Oct 8, 2011 at 13:21
  • 44
    I don't like multiline string as comments. Syntax highlighting marks them as strings, not as comments. I like to use a decent editor that automatically deals with commenting out regions and wrapping multiline comments while I type. Of course, it's a matter of taste. Oct 8, 2011 at 13:31
  • 66
    As a convention I find it helpful to use """ for docstrings and ''' for block comments. In this manner you can wrap ''' around your usual docstrings without conflict.
    – Roshambo
    Dec 18, 2012 at 20:03
  • 25
    While you can use multi-line strings as multi-line comments, I'm surprised that none of these answers refer to the PEP 8 subsection that specifically recommends constructing multi-line comments from consecutive single-line comments, with blank # lines to distinguish paragraphs.
    – Air
    May 21, 2014 at 19:32
105

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.


To protect against link decay, here is the content of Guido van Rossum's tweet:

@BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)

10
  • 3
    triple quoted string (''') indeed work to fulfil multi line comments. Jun 24, 2013 at 6:53
  • Thanks.. Used (''') and (""") to comment out the block but it didn't help me for Django applications. So chose IDLE and there are options like Comment out region and Uncomment regions (shortcut: Alt+3 and Alt+4 respectively) under Format menu. Now it is more easier than ever.. Dec 11, 2013 at 6:53
  • You should also consider using a IDE. Yes, they are hefty, but if used properly they can really boost coding time. I personally used to use PyDev, and now use PTVS (with visual studio). I would definitely reccomend PTVS, as it is really nice to work with, containing the above features along with a lot more - direct integration with virtualenvs, and really good debugging, to say the least
    – Sbspider
    Apr 11, 2014 at 2:42
  • 2
    @HappyLeapSecond I think you should clarify it saying "Python doesn't have a true multiline comment syntax, but supports multiline strings that can be used as comments."
    – ADTC
    Jul 18, 2015 at 10:31
  • 3
    What I want is an easy way to comment out whole blocks of code when testing. Other languages make that easy. Python is just a pain. Feb 26, 2016 at 17:01
74

From the accepted answer...

You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.

This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.

If you try to run this code...

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

You'll get either...

ValueError: invalid \x escape

...on Python 2.x or...

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

...on Python 3.x.

The only way to do multi-line comments which are ignored by the parser is...

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()
4
  • Then, you can use r'raw string' -- r'\xor' == '\\xor'. Jun 29, 2016 at 14:13
  • 3
    Well, any "true" multi-line comment must also be parsed and syntactically valid. C-style comments can't contain a */ as it will terminate the block, for example.
    – user1919238
    Jul 27, 2016 at 9:31
  • 2
    @dan1111 that's obvious that comment cannot include end marker, but that's the only limitation. Sep 29, 2016 at 5:50
  • 20
    ''' "comments" have more limitations. You can only comment out whole statements, whereas comments can comment out parts of expression. Example: In C, you can comment out some list elements: int a[] = {1, 2, /* 3, 4, */ 5};. With Multi line string, you can't do that, as that would put a string inside your list. Sep 29, 2016 at 5:55
43

In Python 2.7 the multiline comment is:

"""
This is a
multilline comment
"""

In case you are inside a class you should tab it properly.

For example:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """
3
  • 26
    triple-quotes are a way to insert text that doesn't do anything (I believe you could do this with regular single-quoted strings too), but they aren't comments - the interpreter does actually execute the line (but the line doesn't do anything). That's why the indentation of a triple-quoted 'comment' is important.
    – Demis
    Jun 9, 2015 at 18:35
  • 17
    This solution is incorrect, the weather2 comment is actually a docstring since it's the first thing in the class. Mar 1, 2017 at 19:16
  • Agree with @KenWilliams. This is not a correct solution. Try putting this in the middle of a function/class, and see how it messes up your formatting and automating code folding/linting.
    – alpha_989
    Feb 2, 2018 at 3:47
30

AFAIK, Python doesn't have block comments. For commenting individual lines, you can use the # character.

If you are using Notepad++, there is a shortcut for block commenting. I'm sure others like gVim and Emacs have similar features.

3
  • 5
    this is incorrect, see the responses on using triple quotes. Feb 23, 2015 at 16:54
  • 12
    @FernandoGonzalezSanchez: It's really not incorrect. This "multi-line string as comment" can be best described as a "pro-tip". The official Python docs say nothing on this, hence the question posted by OP. Feb 23, 2015 at 20:40
  • 9
    That's a PEP for docstrings; there isn't a single mention of "comment" on that page. Feb 24, 2015 at 10:55
19

There is no such feature as a multi-line comment. # is the only way to comment a single line of code. Many of you answered ''' a comment ''' this as their solution.

It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.

Check the official documentation here

1
  • 1
    this should be the accepted answer Dec 6, 2021 at 22:07
17

I think it doesn't, except that a multiline string isn't processed. However, most, if not all Python IDEs have a shortkey for 'commenting out' multiple lines of code.

15

If you put a comment in

"""
long comment here
"""

in the middle of a script, Python/linters won't recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It's better to use

# Long comment
# here.

If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.

If you don’t want to use plugins like the above you can use search and replace like

:.,.+1s/^/# /g

This will replace the first character on the current and next line with #.

0
11

Visual Studio Code universal official multi-line comment toggle. Similar to Xcode shortcut.

macOS: Select code-block and then +/

Windows: Select code-block and then Ctrl+/

8

Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.

Here is an example:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
8

I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string
0
6

Well, you can try this (when running the quoted, the input to the first question should quoted with '):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

Whatever enclosed between """ will be commented.

If you are looking for single-line comments then it's #.

5

Multiline comment in Python:

For me, both ''' and """ worked.

Example:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

Example:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)
5

If you write a comment in a line with a code, you must write a comment, leaving 2 spaces before the # sign and 1 space before the # sign

print("Hello World")  # printing

If you write a comment on a new line, you must write a comment, leaving 1 space kn in the # sign

# single line comment

To write comments longer than 1 line, you use 3 quotes

"""
This is a comment
written in
more than just one line
"""
1
  • The first two advice seem to be coming from PEP 8. Note that for multiline comments PEP 8 tells us to construct them from consecutive single-line comments, not as multiline strings: python.org/dev/peps/pep-0008/#block-comments.
    – Georgy
    Sep 8, 2020 at 16:02
4

On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

"""
A sample
multiline comment
on PyCharm
"""
2
  • 2
    You're saying single quotes create a comment in python 2.7?
    – mcalex
    Jul 9, 2017 at 1:59
  • 3
    Using a single set of quotes creates a string. A single line comment should be prefixed with a #.
    – johanno
    Sep 22, 2017 at 20:43
4

The inline comments in Python starts with a hash character.

hello = "Hello!" # This is an inline comment
print(hello)

Hello!

Note that a hash character within a string literal is just a hash character.

dial = "Dial #100 to make an emergency call."
print(dial)

Dial #100 to make an emergency call.

A hash character can also be used for single or multiple lines comments.

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

Hello

World

Enclose the text with triple double quotes to support docstring.

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

Hello John!

Enclose the text with triple single quotes for block comments.

'''
I don't care the parameters and
docstrings here.
'''
3

Using PyCharm IDE.

You can comment and uncomment lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts). Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

Select all lines then press Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")
3

Yes, it is fine to use both:

'''
Comments
'''

and

"""
Comments
"""

But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.

2

Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.

I am using Anaconda Spyder and it has:

  • Ctrl + 1 - Comment/uncomment
  • Ctrl + 4 - Comment a block of code
  • Ctrl + 5 - Uncomment a block of code

It would comment/uncomment a single/multi line/s of code with #.

I find it the easiest.

For example, a block comment:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================
0
2

Yes, you can simply use

'''
Multiline!
(?)
'''

or

"""
Hello
World!
"""

BONUS: It's a little bit harder, but it's safer to use in older versions, print functions or GUIs:

# This is also
# a multiline comment.

For this one, you can select the text you want to comment and press Ctrl / (or /), in PyCharm and VS Code.

But you can edit them. For example, you can change the shortcut from Ctrl / to Ctrl Shift C.

WARNING!

  1. Be careful, don't overwrite other shortcuts!
  2. Comments have to be correctly indented!

Hope this answer helped. Good luck next time when you'll write other answers!

2

This can be done in Vim text editor.

Go to the beginning of the first line in the comment area.

Press Ctrl+V to enter the visual mode.

Use arrow keys to select all the lines to be commented.

Press Shift+I.

Press # (or Shift+3).

Press Esc.

1

For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:

# This is comment 1
# This is comment 2 
# This is comment 3

For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.

'''
This is
multiline
comment
'''

Also, mention that you can access docstring by a class object like this

myobj.__doc__
2
  • What does this add over the previous answers? Feb 3, 2020 at 17:34
  • My answer contains more details, which may help developer more. Feb 4, 2020 at 3:06
1

A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.

A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.

0
1

Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.

For single line you can use Shift + #.

1

You can use the following. This is called DockString.

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__
2
1

in windows: you can also select the text or code chunks and press ctr + / and do the same if you want to remove the comments. in mac: it should be comment + /

0

I read about all of the drawbacks of the various ways of doing this, and I came up with this way, in an attempt to check all the boxes:

block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
    def __init__(self):
        # create the event object inside raising class
        self.on_thing_happening = Event()

    def doing_something(self):
        # raise the event inside the raising class
        self.on_thing_happening()        
        
        
class ExampleEventHandlingClass():
    def __init__(self):
        self.event_generating_thing = ExampleEventSource()
        # add event handler in consuming class
        event_generating_thing.on_thing_happening += my_event_handler
        
    def my_event_handler(self):
        print('handle the event')
]#'''


class Event():
 
    def __init__(self):
        self.__eventhandlers = []
 
    def __iadd__(self, handler):
        self.__eventhandlers.append(handler)
        return self
 
    def __isub__(self, handler):
        self.__eventhandlers.remove(handler)
        return self
 
    def __call__(self, *args, **keywargs):
        for eventhandler in self.__eventhandlers:
            eventhandler(*args, **keywargs)

Pros

  1. It is obvious to any other programmer this is a comment. It's self-descriptive.
  2. It compiles
  3. It doesn't show up as a doc comment in help()
  4. It can be at the top of the module if desired
  5. It can be automated with a macro.
  6. [The comment] is not part of the code. It doesn't end up in the pyc. (Except the one line of code that enables pros #1 and #4)
  7. If multi-line comment syntax was ever added to Python, the code files could be fixed with find and replace. Simply using ''' doesn't have this advantage.

Cons

  1. It's hard to remember. It's a lot of typing. This con can be eliminated with a macro.
  2. It might confuse newbies into thinking this is the only way to do block comments. That can be a pro, just depends on your perspective. It might make newbies think the line of code is magically connected to the comment "working".
  3. It doesn't colorize as a comment. But then again, none of the answers that actually address the spirit of the OP's question would.
  4. It's not the official way, so Pylint might complain about it. I don't know. Maybe; maybe not.

Here's an attempt at the VS Code macro, although I haven't tested it yet:

{
    "key": "ctrl+shift+/",
    "command": "editor.action.insertSnippet",
    "when": "editorHasSelection"
    "args": {
        "snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
    }
}
2
  • what is the official way that pylint wont complain about? pylint complains about the use of ''' with "pylint: String statement has no effect" Dec 3, 2022 at 21:14
  • @user1689987, there is no official way provided. That's the problem. You could assign that whole "comment", which is just a string, to a dummy variable and that warning will go away. I would name the variable comment
    – toddmo
    Dec 4, 2022 at 14:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.