1397

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

/*

*/
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Dungeon Hunter
  • 19,827
  • 13
  • 59
  • 82
  • 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. – Victor Zamanian Mar 14 '17 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). – Brandon Barney Jul 07 '17 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 06 '17 at 03: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. – Brandon Barney Aug 06 '17 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 '18 at 18:41
  • In Notepad++ ctrl+k comments the lines selected with # – takluiper Nov 19 '18 at 13:47
  • @VictorZamanian Python **is not** "an interpreted language". It has the same compilation model as Java or C#, just with run-time type checks rather than manifest typing. – Karl Knechtel Sep 23 '22 at 16:05
  • @KarlKnechtel From Wikipedia: "Most Python implementations (including CPython) include a read–eval–print loop (REPL), permitting them to function as a command line interpreter for which users enter statements sequentially and receive results immediately." – Victor Zamanian Sep 24 '22 at 18:33

27 Answers27

2134

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.

larsks
  • 277,717
  • 41
  • 399
  • 399
Petr Viktorin
  • 65,510
  • 9
  • 81
  • 81
  • 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 08 '11 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. – Petr Viktorin Oct 08 '11 at 13:21
  • 41
    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. – Sven Marnach Oct 08 '11 at 13:31
  • 2
    @Sven, [my editor](http://kate-editor.org/) happens to mark them as comments, unless used in an expression. Maybe you could (open a request to) fix the syntax highlighting for your editor? Python does ignore these, so they *are* comments. But yes, it's a matter of taste. – Petr Viktorin Oct 08 '11 at 13:48
  • 1
    While my editor highlights them correctly, I agree that just using ctrl-something to comment/uncomment several lines is simpler and looks better in my opinion (but then I'm also not using /* */ in Java, C# or c++). Just a matter of taste I assume ;) – Voo Oct 08 '11 at 14:30
  • 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 '12 at 20:03
  • 1
    Though not optimally space efficient, I use `'''` when I only want a small comment in a line of code. – emmagras Jan 10 '13 at 22:02
  • 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](http://legacy.python.org/dev/peps/pep-0008/#block-comments) that specifically recommends constructing multi-line comments from consecutive single-line comments, with blank `#` lines to distinguish paragraphs. – Air May 21 '14 at 19:32
  • 4
    @AirThomas: Yeah, I agree. Not terribly sure if it's fair to change a 200+ answer from "Use this, it's great and BDFL-blessed" to "You can use this, but it's not something you'd want to commit to the repo", but I went ahead and made the change. – Petr Viktorin May 26 '14 at 14:34
  • 1
    Additionally whether you use triple-apostrophes, triple-quotation marks or hash/pound comment tokens may depend if you use any third party source code tools that clean up or create document generators that pull text from the source. – DevPlayer Sep 10 '14 at 13:27
  • 1
    I would be cautious about using triple quotes. In Python 2 it seems fine, but I have found libraries that throw errors in Python 3, when \N is in the triple quotes...as it's read like a doc string. Here's an example: ''' (i.e. \Device\NPF_..) ''' That will result in an error as it reads \N and no longer acts like a true comment, but interprets what is in there. Which makes me wonder if compiling is also interpreting the triple quotes... which a real comment shouldn't be considered at compile time, right? – continuousqa Sep 23 '14 at 17:43
  • Yes, \N introduces a named Unicode character (try `"\N{BLACK STAR}"` in Python 3). It does the same thing in Python 2 Unicode strings as well. You'll have the same problem with `\x`, `\u`, and `\U`. – Petr Viktorin Sep 24 '14 at 14:57
  • 2
    If your comment includes a long piece of text that you'd like to be able to copy-paste, either you have to put it all on one line or use block comments. Another vote for block comments. – Eyal Mar 30 '15 at 14:17
  • 4
    fyi, using string-literals (single or tripe-quotes) for comments can lead to strange problems. For example, I recently got an `Indentation Error...` which I finally figured out was due to there being a triple-quoted '''comment''' right before an `elif` statement. Since the '''string-literal''' is actually just code that does nothing (not a comment) it does affect indentations. – Demis Jun 09 '15 at 18:33
  • 1
    @PetrViktorin: The tweet link seems to have changed to https://twitter.com/gvanrossum/status/112670605505077248. Would you please put the actual text in your answer to protect against link decay? – unutbu Jul 18 '15 at 12:03
  • @HappyLeapSecond: Thanks, I corrected the link. But the tweet is already paraphrased in the answer; copying it wouldn't bring anything new. – Petr Viktorin Jul 18 '15 at 13:35
  • I am allways amazzed about Python's simplicity. Comment are strings in the source code. So comments interpreted by the interpreter as strings, but they are forgotten by the interpreter in the same CPU click as the reference counter of the object is 0. So we needn't any precompiler or soficticated IDE to handle the multiline comments. – jshepherd Oct 06 '16 at 07:55
  • 2
    Using `'''` to multi-line comment is terrible procedure as it is not ignored by the interpreter like an actual comment is. It is garbage-collected instantly, but the code is still using resources. – DeeJayh Jan 16 '18 at 02:28
  • 2
    I have to say this is an *extremely* poor choice of syntax (the fault of the Python devs, not you). Why? If for not for the many reasons in other comments because most IDE's including Jupyter automatically give you 2 single quotes instead of 1, thus getting 3 is a pain. Yet it would not be worth it to change the behavior. The syntax should just be like the many other more sensible choices out there including `/* */`. – Hack-R Feb 03 '18 at 15:46
  • 1
    If you're using an IDE, use its “comment” shortcut – e.g. Ctrl+/ in Jupyter. (And yes, Jupyter automatically adding stuff I didn't actually type drives me up the wall.) – Petr Viktorin Feb 04 '18 at 10:00
  • 3
    This answer is incorrect. multiline strings are not the same as a comment. A comment is whitespace and has no semantic interpretation. However, a multiline comment does. – Prof Mo Feb 22 '18 at 16:26
  • 1
    @Roshambo I use your convention, and more: `'''block comment'''` instead of `pass`. I find this helpful to explain an empty except-clause or if-else-clause. – Bob Stein Jul 16 '18 at 13:24
  • Btw, the whole multiline string can be toggled "on/off" by putting a single `#` before the closing `'''`. Now, if you put another `#` before the opening `'''`, the whole section will be code. If you remove the first `#` again, it will be back to multiline string. Really helpful to temporarily disable several/lots of lines of code easily (unless they contain `'''` multiline strings, of course). But then again, you could use double-quotes for your toggle. – riha Jun 13 '19 at 14:38
  • I am getting an `indentation error`. I did indent the apostrophes correctly. Could you please help me out? is it necessary to indent the apostrophes just like the previous line? Or can I start it from the start of the new physical line? – Kaushik Feb 09 '20 at 22:08
  • `Pep8` recommending multi-line strings is yet another big fail on that spec. It's one of the worst things for a language already having major issues. In an age of 3K laptops: 79-character lines (which much of that taken up by the 4-space indentations) anyone?? – WestCoastProjects Sep 19 '20 at 17:06
  • @javadba PEP 8 does not recommend multi-line strings for comments. Also, PEP 8 [explicitly says](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) you can agree on a different line length. (Myself, I like to have several files open side-by-side on the big screen, and also see the whole line on a phone.) – Petr Viktorin Sep 21 '20 at 07:28
  • @PetrViktorin Thx for pointing that out! There are many users of `PEP8` that are not aware of that option to use the 99 length. – WestCoastProjects Sep 21 '20 at 10:36
  • Yeah, if a string is created without context in a python file, it will be skipped. – Jacob Ward Dec 03 '20 at 01:19
102

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! :-)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 3
    triple quoted string (''') indeed work to fulfil multi line comments. – Varun Bhatia Jun 24 '13 at 06: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.. – Saurav Kumar Dec 11 '13 at 06: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 '14 at 02:42
  • @ADTC: In acknowledgment of [Petr Viktorin's answer](http://stackoverflow.com/a/7696966/190597), I edited my answer to read "Python *does* have a multiline string/comment syntax". – unutbu Jul 18 '15 at 09:28
  • 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 '15 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. – Albert Godfrind Feb 26 '16 at 17:01
  • the benefit of multiline comments when developing is helpful when some of the lines in the area are commented and you don't want to confuse them with the good lines of code – quemeful Oct 20 '16 at 21:16
  • I would still consider it bad style, even though Guido says it's ok. Not suitable for releases, but a quick and dirty solution while testing and debugging. Another way to keep around old code while edition a function is to just put `return` command above it. – Bachsau Oct 22 '18 at 10:23
  • "you would be right to say it is not guaranteed as part of the language specification." - *Bytecode* is not guaranteed as part of the language specification. The implementation is free to interpret Python code line for line as text, AOT compile it into machine code, or whatever it wants, without necessarily creating bytecode at all. So it's rather strange to pick one very specific implementation detail and call it out in this fashion. – Kevin Apr 27 '19 at 04:41
  • You can always use ' ' ' (triple quotation marks) to create a multi-line string. This is also good because strings get ignored if they are put into code without context (i.e. if they are not assigned to a variable) – Jacob Ward Dec 03 '20 at 01:21
69

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()
Aya
  • 39,884
  • 6
  • 55
  • 55
  • Then, you can use `r'raw string'` -- `r'\xor' == '\\xor'`. – GingerPlusPlus Jun 29 '16 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. –  Jul 27 '16 at 09:31
  • 2
    @dan1111 that's obvious that comment cannot include end marker, but that's the only limitation. – el.pescado - нет войне Sep 29 '16 at 05:50
  • 17
    `'''` "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. – el.pescado - нет войне Sep 29 '16 at 05:55
40

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
   """
ncica
  • 7,015
  • 1
  • 15
  • 37
SomeAnonymousPerson
  • 3,173
  • 1
  • 21
  • 22
  • 25
    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 09 '15 at 18:35
  • 17
    This solution is incorrect, the `weather2` comment is actually a docstring since it's the first thing in the class. – Ken Williams Mar 01 '17 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 02 '18 at 03:47
29

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.

Community
  • 1
  • 1
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
17

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RATAN KUMAR
  • 553
  • 6
  • 11
16

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anti Earth
  • 4,671
  • 13
  • 52
  • 83
14

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alpha_989
  • 4,882
  • 2
  • 37
  • 48
10

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+/

Edison
  • 11,881
  • 5
  • 42
  • 50
7

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,'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
d.nedelchev
  • 116
  • 1
  • 5
7

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
j-i-l
  • 10,281
  • 3
  • 53
  • 70
5

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
K_holla
  • 124
  • 1
  • 3
4

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Viraj Wadate
  • 5,447
  • 1
  • 31
  • 29
4

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
"""
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 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: https://www.python.org/dev/peps/pep-0008/#block-comments. – Georgy Sep 08 '20 at 16:02
3

On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

"""
A sample
multiline comment
on PyCharm
"""
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alvin George
  • 14,148
  • 92
  • 64
3

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.
'''
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Madan Sapkota
  • 25,047
  • 11
  • 113
  • 117
2

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.")
0m3r
  • 12,286
  • 15
  • 35
  • 71
2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rajkamal Mishra
  • 121
  • 1
  • 9
1

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!
# =============================================================================
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aniltilanthe
  • 4,587
  • 1
  • 18
  • 17
1

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!

me1234
  • 37
  • 9
1

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.

Liker777
  • 2,156
  • 4
  • 18
  • 25
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
YouKnowWhoIAm
  • 334
  • 1
  • 12
0

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

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__
shafik
  • 6,098
  • 5
  • 32
  • 50
0

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__
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
unknown
  • 322
  • 6
  • 25
0

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 + /

Seyma Kalay
  • 2,037
  • 10
  • 22
-1

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}]#'''"
    }
}
toddmo
  • 20,682
  • 14
  • 97
  • 107
  • what is the official way that pylint wont complain about? pylint complains about the use of ''' with "pylint: String statement has no effect" – user1689987 Dec 03 '22 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 04 '22 at 14:47