282

OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,

"""Hello, I am a 
   multiline comment"""

and

'''Hello, I am a 
   multiline comment'''

But technically speaking these are strings, correct?

I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CoolGravatar
  • 5,408
  • 7
  • 35
  • 42
  • 8
    If you can do it as a string why add more ways? – Brody Dec 29 '08 at 05:22
  • 15
    Just wanted to add, that it fails if what you are trying to comment happens to also have comments/multi-line strings. And that of course, is why we need them. – nycynik Apr 02 '12 at 14:28
  • 58
    @S.Lott I think it's a useful question. In order to understand why Python is good, it's important to understand the design decisions that were made (and on-going decisions that are still being made). The question isn't argumentative or combative; it's curious. No need to be so harsh about curiosity. – Mark E. Haase Jun 20 '12 at 13:01
  • The same what if applies of course if your code already has multi-line comments... – Steve Barnes Mar 09 '15 at 19:56
  • 9
    If you need a multi line comment for cod just `if False:` the code – AturSams Mar 11 '15 at 13:39
  • 9
    @Brody Because strings are processed. Comments are ignored. There are problems with using strings as comments. Just look around :) – ADTC Jul 18 '15 at 05:39
  • 1
    @Brody as ADTC said, this doesn't work in many cases. Take sub-line comments: the code `foo(bar /*comment*/, baz)` in any C-like language has no equivalent in Python as a string literal there is a syntax error. – Oliver Nov 08 '20 at 05:28
  • @Oliver But of course! The idiomatic way to comment out a block in C/C++ is `#if 0`…`#endif`. – kkm inactive - support strike Mar 03 '23 at 13:14
  • 1
    @AturSams, and then reindent the commented out code following `if False:`. Thanks, but no. I understand I'm continuing where you left off 8 years ago, but what is indeed telling, is that your comment got 8 upvotes. I interpret this relatively high number as some people having literally _fallen in love_ with Python to the degree of losing their mind... – kkm inactive - support strike Mar 03 '23 at 13:20

18 Answers18

286

I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments".

Guido has tweeted about this:

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

Simeon Leyzerzon
  • 18,658
  • 9
  • 54
  • 82
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 30
    See [Guido's tweet](https://twitter.com/gvanrossum/status/112670605505077248) on this. – Petr Viktorin Oct 08 '11 at 13:07
  • 18
    one disadvantage of mix multi-line string and block comments is IDE has no idea what you want thus can't show comment in different style as needed. – Baiyan Huang Sep 17 '12 at 03:58
  • 27
    It also makes it impossible to comment out code with multi-line strings (and can lead to indentation errors if you're not careful). Ew! – Mike Graham Sep 17 '12 at 21:15
  • 4
    I have worked in a lot of fields where if your code contains commented out code then your code is rejected and you may even find yourself invited to update your CV. Either remove the code that is not needed, not a problem if the code is under version control, or use `if False:` before the code that needs to be disabled. – Steve Barnes Mar 09 '15 at 19:55
  • 13
    @SteveBarnes agree that big blocks of commented-out code in production are bad. But I don't understand why `if False` is better. It accomplishes exactly the same thing, while being less clear (since it isn't as obvious at a glance that the block of code has been disabled). –  Jul 27 '16 at 09:37
  • @dan1111 - I personally prefer removing vestigial code you can always get it back from the VCS if needed. Comments should be comments. – Steve Barnes Jul 27 '16 at 17:10
  • 1
    @SteveBarnes yes I agree (though commenting out temporarily can be useful during the development process). But given that someone is commenting out a block of code. I'm not sure why `if false` is better. –  Jul 28 '16 at 08:52
  • Some prefer if False: # with a comment why - as it is clearly code that is not to be executed but is not confused with comments. A lot of IDEs do allow you to toggle commenting of a block of code on or off. – Steve Barnes Jul 28 '16 at 17:17
  • 3
    @SteveBarnes Thanks for deciding these things for us under all circumstances - just like Guido does. I have worked at the largest companies and there are times and places for this degree of strictness. And not.. – WestCoastProjects Nov 23 '16 at 03:50
  • @javadba - Honoured that I may be to be compared to Guido I was not attempting to dictate but rather to explain the reasoning behind the decision. In some of the industries that I have worked in commented out code is a rejection reason - then again code that is never executed & tested is as well - there are MISRA rules against both for example. – Steve Barnes Nov 23 '16 at 07:44
  • @SteveBarnes It is disallowed @ google: I think i'm getting a little over excited here: you're correct in this. – WestCoastProjects Nov 23 '16 at 07:52
61

Multi-line comments are easily breakable. What if you have the following in a simple calculator program?

operation = ''
print("Pick an operation:  +-*/")
# Get user input here

Try to comment that with a multi-line comment:

/*
operation = ''
print("Pick an operation:  +-*/")
# Get user input here
*/

Oops, your string contains the end comment delimiter.

Steve Losh
  • 19,642
  • 2
  • 51
  • 44
  • 182
    The nicest thing about this answer is how it is handled by SO's syntax highlighter. – Nietzche-jou Dec 29 '08 at 15:50
  • I didn't even notice... I rest my case. :) – Steve Losh Dec 30 '08 at 19:39
  • 77
    This is one of the many reasons why we have escape characters, I don't see that as a good reason to NOT have support for multi-line comments. – Natalie Adams Apr 01 '10 at 16:17
  • 3
    No escape characters would help here. If the */ in the string is escaped to allow the comment, it would show up in the string when it's **not** commented. Otherwise it breaks the comment. If you want to add even more escapes to strings to allow for comments, I think that would add unnecessary complexity to the language's string syntax. – Steve Losh Apr 02 '10 at 01:21
  • 38
    I don't understand your logic - perhaps my comment wasn't clear enough. If we used \ as an escape character: print("Pick an operation: +-*\/") "*/" no longer denotes a ending comment block as literally / will be printed. Go ahead and test this in C++. In fact SO's syntax highlighter will show that is valid. This is not a complex subject, it has existed for years in other languages. I would ask that you update your post to include the use of escape characters to show that you CAN use "*/" in your code. – Natalie Adams Apr 02 '10 at 20:57
  • 3
    @NathanAdams: Yes, and now you've introduced another escape character into strings that you have to use *only* because multi-line commenting sucks, just like I said. And what about raw strings? Do those get the escape too (which would be the ONLY escape they'd have), or are they still broken? – Steve Losh Oct 19 '11 at 15:52
  • What other characters does one need to escape in a multi-line comment? – Natalie Adams Oct 21 '11 at 15:58
  • 27
    what if your code contains ''' . oops your code contains the end comment delimiter – siamii Nov 15 '11 at 00:57
  • 27
    Multi-line comments aren't inherently breakable; it's just that most implementations of them are (including Python's). The obvious way to do multi-line comments in Python, to my mind, is to just let me start a comment block with `#:` and use indentation to show when the comment's ended. It's clean, consistent, and handles nesting perfectly. – GatesDA Jun 15 '12 at 07:53
  • in D you can use /+ +/ *shameless ads* – Quonux Jul 27 '13 at 22:23
  • Some explanation for questioning minds: Sure this will spoil multiline comment as parser is in "looking for closing \*/" mode (so to speak) after first encountering '/*'. However - if you place opening '/*' in your string - all will work fine and comment will not be messed up. – Artur Oct 03 '13 at 10:38
  • 1
    That is a contrived example – StanOverflow Sep 10 '14 at 14:49
  • 14
    -1. This problem was solved in C, or maybe one of its predecessors. So from 1972 onwards, this answer has been invalid. – Dawood ibn Kareem Nov 12 '14 at 20:59
  • I would argue that any single-line commenting syntax is also just as "easily breakable" by new line characters... (?) -- I mean... if we're talking extremely minor, rare, and addressable edge cases... – Code Jockey Apr 11 '19 at 19:36
40

Triple-quoted text should NOT be considered multi-line comments; by convention, they are docstrings. They should describe what your code does and how to use it, but not for things like commenting out blocks of code.

According to Guido, multiline comments in Python are just contiguous single-line comments (search for "block comments").

To comment blocks of code, I sometimes use the following pattern:

if False:
    # A bunch of code
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
  • 7
    Seems like Guido [chanded his mind](https://twitter.com/#!/gvanrossum/status/112670605505077248) since then. – Petr Viktorin Oct 08 '11 at 13:02
  • 5
    regarding the "if false:" solution, the thing is that in python as it works with tabs, you'd have to tab in all the code under the "if False:". And untab the chunk afterwards. So you'd have to be pretty nifty with your text editor. – barlop Oct 19 '13 at 17:53
  • 3
    if you use a decent editor, that should be the same amount of time as */ – AturSams Mar 11 '15 at 13:43
  • @barlop yup - learn your editors! This is typically achievable in under a second in vim with `V}>>` – Kenan Banks Apr 04 '16 at 12:48
  • Multi-line/triple-quoted strings don't have to be docstrings, and vice versa. A docstring is *"a string literal that occurs as the first statement in a module, function, class, or method definition"*, whether or not it's multi-line. Unused (unassigned or not otherwise used in a statement/expression) literals elsewhere in your code, string or otherwise, are discarded at compile time. – jonrsharpe Mar 06 '21 at 11:02
32

This likely goes back to the core concept that there should be one obvious way to do a task. Additional comment styles add unnecessary complications and could decrease readability.

  • 11
    That's the issue, I believe: Using a string as a comment is not obvious and violates the "one way to do a task" principle, since there are two ways to do comments: strings and `#`. – GatesDA Jun 15 '12 at 08:10
  • 1
    But its not significantly different than what you have in C-based languages: /* vs // , so i don't see how its significantly worse. – B Robster Jul 20 '12 at 21:25
  • // , Consider WHY someone would want a multi-line comment. Good reasons: ... I can't really think of any beyond "I don't have to type as many of these # doohickeys" and "I need to display this particular comment in a very precise way, and that precise way doesn't allow for preceding #." Say someone wants to do an ASCII diagram, or put some reference javascript code to be copied and pasted if a specific problem comes up. The one obvious way to do a task, here, doesn't cover the edge cases of that task. I agree, though, that additional comment styles are BAD. – Nathan Basanese Jun 10 '15 at 09:00
  • 4
    "I don't have to type as many of these # doohickeys". That is precisely why pretty much all languages have block comments (/* ..*/). Believe it or not, but I like to document what my code does: the inputs, the outputs, the algorithms used, the parameters ... That is a lot of text that also gets modified. The restriction to only single-line comments is just plain ridiculous. Note that I do NOT advocate the approach for commenting out code - although that is often handy when trying alternate approaches, as long as the well known possible side effects are understood. – Albert Godfrind Apr 10 '16 at 09:41
  • 3
    The other thing I resent about python is that it is essentially a one-man designed language. Whatever Guido says is the truth ... So we have all those odd incompatibilities between language versions. Why ? Because Guido said so ... – Albert Godfrind Apr 10 '16 at 09:42
12

Well, the triple-quotes are used as multiline comments in docstrings. And # comments are used as inline comments and people get use to it.

Most of script languages don't have multiline comments either. Maybe that's the cause?

See PEP 0008, section Comments

And see if your Python editor offers some keyboard shortcut for block commenting. Emacs supports it, as well as Eclipse, presumably most of decent IDEs does.

Abgan
  • 3,696
  • 22
  • 31
9

From The Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

Jeremy Cantrell
  • 26,392
  • 13
  • 55
  • 78
  • Yet Python doesn't follow this at all.. 4 different ways to exit a program for example. Many other examples. – mczarnek Jan 08 '22 at 21:36
7

To comment out a block of code in the Pycharm IDE:

  • Code | Comment with Line Comment
  • Windows or Linux: Ctrl + /
  • Mac OS: Command + /
Bob Stein
  • 16,271
  • 10
  • 88
  • 101
Craig S. Anderson
  • 6,966
  • 4
  • 33
  • 46
5

Personally my comment style in say Java is like

/*
 * My multi-line comment in Java
 */

So having single-line only comments isn't such a bad thing if your style is typical to the preceding example because in comparison you'd have

#
# My multi-line comment in Python
#

VB.NET is also a language with single-line only commenting, and personally I find it annoying as comments end up looking less likes comments and more like some kind of quote

'
' This is a VB.NET example
'

Single-line-only comments end up having less character-usage than multi-line comments, and are less likely to be escaped by some dodgy characters in a regex statement perhaps? I'd tend to agree with Ned though.

Kieran Senior
  • 17,960
  • 26
  • 94
  • 138
3

I solved this by downloading a macro for my text editor (TextPad) that lets me highlight lines and it then inserts # at the first of each line. A similar macro removes the #'s. Some may ask why multiline is necessary but it comes in handy when you're trying to "turn off" a block of code for debugging purposes.

kati
  • 31
  • 1
3
# This
# is
# a 
# multi-line
# comment

Use comment block or search and replace (s/^/#/g) in your editor to achieve this.

recursive
  • 83,943
  • 34
  • 151
  • 241
3

For anyone else looking for multi-line comments in Python - using the triple quote format can have some problematic consequences, as I've just learned the hard way. Consider this:

this_dict = {
    'name': 'Bob',

"""
This is a multiline comment in the middle of a dictionary
"""

    'species': 'Cat'
}

The multi-line comment will be tucked into the next string, messing up the 'species' key. Better to just use # for comments.

Itamar Mushkin
  • 2,803
  • 2
  • 16
  • 32
1

There should only be one way to do a thing, is contradicted by the usage of multiline strings and single line strings or switch/case and if, different form of loops.

Multiline comments are a pretty common feature and lets face it the multiline string comment is a hack with negative sideffects! I have seen lots of code doing the multiline comment trick and even editors use it.

But I guess every language has its quirks where the devs insist on never fixing it. I know such quirks from the java side as well, which have been open since the late 90s, never to be fixed!

werner
  • 71
  • 6
0

Multiline comments using IDLE on:

  • Mac OS X, after code selection, comment a block of code with Ctrl+3 and uncomment using Ctrl+4.

  • Windows, after code selection, comment a block of code with Ctrl+Alt+3 and uncomment using Ctrl+At+4.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

Assume that they were just considered unnecessary. Since it's so easy to just type #a comment, multiline comments can just consist of many single line comments.

For HTML, on the other hand, there's more of a need for multiliners. It's harder to keep typing <!--comments like this-->.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
stalepretzel
  • 15,543
  • 22
  • 76
  • 91
  • 4
    this is not the point - there are obvious use cases for both single line and multi line comments. I have used them both extensively in other languages (though I know python purists don't care about other languages). ;) – johndodo Aug 05 '11 at 07:57
  • 1
    try doing this with 200 lines of code, that you have to take out, put back in, then take out again. Typing 200 initial #'s gets old real fast. – DragonLord May 14 '12 at 04:14
0

This is just a guess .. but

Because they are strings, they have some semantic value (the compiler doesn't get rid of them), therefore it makes sense for them to be used as docstrings. They actually become part of the AST, so extracting documentation becomes easier.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hasen
  • 161,647
  • 65
  • 194
  • 231
0

Because the # convention is a common one, and there really isn't anything you can do with a multiline comment that you can't with a #-sign comment. It's a historical accident, like the ancestry of /* ... */ comments going back to PL/I,

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
0

Besides, multiline comments are a bitch. Sorry to say, but regardless of the language, I don't use them for anything else than debugging purposes. Say you have code like this:

void someFunction()
{
    Something
    /*Some comments*/
    Something else
}

Then you find out that there is something in your code you can't fix with the debugger, so you start manually debugging it by commenting out smaller and smaller chuncks of code with theese multiline comments. This would then give the function:

void someFunction()
{ /*
    Something
   /* Comments */
   Something more*/
}

This is really irritating.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
martiert
  • 1,636
  • 2
  • 18
  • 23
  • 3
    uh great, but Python doesn't have `/*`-style comments. – Kenan Banks Dec 31 '10 at 15:03
  • 19
    Right, since python doesn't have real multiline comments it was kind of hard giving examples in python. – martiert Dec 31 '10 at 15:24
  • 2
    I personally don't understand the problem. Just delete the extra */. Or use // to comment out single lines if you need to be precise. – Natalie Adams Mar 02 '12 at 02:04
  • 4
    There are several languages (many of them functional for whatever reason) which allow nested comments. Search for "nested" in http://rosettacode.org/wiki/Comments for examples. – Keith Apr 19 '12 at 21:07
  • 1
    well yeah it would be irritating to put a multi-line comment in a multi-line comment. And while I only remember a bit of my program at a time, I at least remember which part of my program I am looking at and so which I have commented out. But if you can't even remember that, then, you can use the fact that some IDEs make italic what is a comment. Anyhow obviously for such a tiny function, you may as well use single line comments. But if commenting out a big chunk of program, you need a multi-line comment really. or a text editor with that feature. – barlop Oct 19 '13 at 17:50
-1

I remember reading about one guy who would put his multi-line comments into a triple-quoted variable:

x = '''
This is my
super-long mega-comment.
Wow there are a lot of lines
going on here!
'''

This does take up a bit of memory, but it gives you multi-line comment functionality, and plus most editors will highlight the syntax for you :)

It's also easy to comment out code by simply wrapping it with

x = '''

and

'''
turvyc
  • 95
  • 1
  • 3