How to comment out a block of code in Python [duplicate]
Asked Answered
I

19

554

Is there a mechanism to comment out large blocks of Python code?

Right now, the only ways I can see of commenting out code are to either start every line with a #, or to enclose the code in triple quotes: """.

The problem with these is that inserting # before every line is cumbersome and """ makes the string I want to use as a comment show up in generated documentation.

After reading all comments, the answer seems to be "No".

Inertia answered 23/3, 2009 at 22:17 Comment(6)
This question was answered previously in Stack Overflow question Why doesn't Python have multiline comments?.Darter
Additional guidelines of professional practice, "Don't use triple-quotes", distinguishes it from other posts ...Deckle
Sigh. One more useful and non-duplicate question marked as duplicate... This one asks for a solution, while the other one takes the answer (namely that no, there's no solution) as a prerequisite for asking what it has to ask.Monoclinous
Ctrl + / works for PyCharmShaving
<snark>Perl allows you to use the documentation syntax for block commenting in such a way that it does NOT end up in the documentation. That's why we have more than one way to do things. It's called 'flexibility'. <\snark>Gord
For Jupyter, to comment use Crtl + / and uncomment use Crtl - /Scholem
G
483

Python does not have such a mechanism. Prepend a # to each line to block comment. For more information see PEP 8. Most Python IDEs support a mechanism to do the block-commenting-with-hash-signs automatically for you. For example, in IDLE on my machine, it's Alt+3 and Alt+4.

Don't use triple-quotes; as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.

Goingson answered 23/3, 2009 at 22:20 Comment(22)
Geany also has this. Right click, Format, Comment Line(s).Askance
For non-Americans, that's a "hash" sign.Galloromance
in Notepad++ that's Ctrl+K (v.5.9.2) for any supported languageNonflammable
In Eclipse, toggling comment for a selected block of code is performed using Ctrl+/. You do not need to select the code if it is only a single line.Gaines
Even for Americans, "pound" should be £ or ₤.Airedale
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.Football
In Vim with NERDCommentor installed, it is as easy as selecting the portion of code to be commented and pressing \c<space>Workable
In PyCharm, it's CTRL-/Quagmire
You can't triple-quote code that contains triple-quotes.Wakeen
Actually, that symbol is called an octothorp. Please stop using local slang terms - few Americans call it a hash, and few non-Americans call it a pound, but nobody ever refers to anything else when they say octothorp. Except the person who chooses to defy this definitive answer by using it to mean something else.Keishakeisling
The creator of python actually suggests to use multi-line strings as block comments, so I would say your statement "Don't use triple-quotes" isn't appropriate.Ber
@JesseWebb: He wrote that about two and a half years after this answer, though, so he changed his mind. :)Goingson
From a Microsoft developer, # is a "sharp" signLeadership
@JesseWebb Although it might be noted to use triple quotes, I found a bug in python library I was using (Pyshark) with regards to Python 3. there used to be this line in a triple quote comment in the pyshark library: (i.e. \Device\NPF_..). This was ignored in Python2 and ran fine, but Python 3 threw this error: "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 14-15: malformed \N character." Since then, I avoid triple quotes.Turgeon
Ctrl+/ in PyCharm will do comment / uncomment the highlighted rowsApostil
As said above, Python's creator actually suggests using triple quotes as block comments. Most editors will detect a triple-quoted string used in this way (not assigned or used in any way) and color it with the comment color. You can use ''' to comment blocks of code containing """ and vice-versa.Tarmac
Calling it a hash, hash symbol, or number sign is the best bet. Especially now in 2017 hash is one of the most common ways to refer to that symbol. Nobody refers to it as an octothorpe except people trying to show off that they know that it's called an octothorpe. oxfordlearnersdictionaries.com/us/definition/english/…Baldachin
It's a sharp sign for musicians.(e.g A major scale: A B C# D E F# G# A)Chrominance
@johnktejik This '♯' is a sharp sign. '#' this is the number sig.Lotus
The correct term is 'number sign' (Unicode U+0023). It is also indexed under 'octothorpe', 'crosshatch', 'pound sign', and 'hash'.Chukchi
few Americans call it a hash, and few non-Americans call it a pound The number of Americans that call it a hash plus the number of non-Americans that call it a pound is at least 1,000 times the number of people on Earth that call it octothorpe.Minny
And here this whole time I thought it was called a comment-symbolRutilant
E
105

Hide the triple quotes in a context that won't be mistaken for a docstring, eg:

'''
...statements...
''' and None

or:

if False: '''
...statements...
'''
Epigoni answered 24/3, 2009 at 0:47 Comment(4)
I don't think that is a good advice, you are adding complexity to your code without any real benefit. Someone reading that would have to figure out why is that code there and what is it suppouse to do.Gladis
What if the code you want to comment out already contains triple-quoted strings?Wakeen
luckily for me it did not.Thorma
@keithThompson then use the other kind of triple quoted stringHeighttopaper
M
99

The only cure I know for this is a good editor. Sorry.

Mcnary answered 23/3, 2009 at 22:22 Comment(2)
Clearly, all Real Python Programmers use ed, where this problem is easily solved with: 12,31s/^/#/Elishaelision
vim with nerdcommenter. Select the block you want and ,c<space>Bolus
L
48

The only way you can do this without triple quotes is to add an:

if False:

And then indent all your code. Note that the code will still need to have proper syntax.


Many Python IDEs can add # for you on each selected line, and remove them when un-commenting too. Likewise, if you use vi or Emacs you can create a macro to do this for you for a block of code.

Lux answered 23/3, 2009 at 22:19 Comment(5)
The op mentioned that they do not want the comments to appear as doc strings.Statesmanship
-1 retracted. That's a clever idea, though it may mean that the comments need comments :)Statesmanship
That solution is similar to just commenting out the code, except that you add four spaces instead of # and that you also need to add "if False:" line.Pugh
I was doing some script hacking and that is what I came up with. (So, +1). It's very slick that I can simply write "if False:", push the block over 1 tab and I'm done. I've used more than one editor where the method is nothing more than,highlight the block, then press tab. Strangely enough, I asked the original question for a friend, wanting to show off S.O. back when it was new.Inertia
Ctrl+ / or Ctrl + Shift+/ in PyCharm does the sameEppes
E
43

In JetBrains PyCharm on Mac use Command + / to comment/uncomment selected block of code. On Windows, use CTRL + /.

Excellence answered 4/3, 2013 at 7:35 Comment(5)
This also works for PyCharm Community Edition, which is free and open-sourced.Elsieelsinore
thanks! works with text wrangler as wellHubbell
CTRL+/ on Windows doesn't work for a Swedish keyboard layout.Pede
Also works for VSCode on macOSBreaker
Also works on VSCode on WindowsGrume
G
29

M-x comment-region, in Emacs' Python mode.

Gallinule answered 23/3, 2009 at 22:33 Comment(1)
M-; (comment-dwim) tooPugh
O
18

At least in VIM you can select the first column of text you want to insert using Block Visual mode (CTRL+V in non-windows VIMs) and then prepend a # before each line using this sequence:

I#<esc>

In Block Visual mode I moves to insert mode with the cursor before the block on its first line. The inserted text is copied before each line in the block.

Ostmark answered 1/10, 2009 at 21:27 Comment(0)
S
13

In vi:

  • Go to top of block and mark it with letter a.
  • Go to bottom of block and mark it with letter b

Then do

:'a,'b s!^!#!
Sanfordsanfourd answered 16/9, 2010 at 17:48 Comment(1)
Or: CTRL+V (and select lines) => :s/^/#/g If text highlighting is bothering you => :nohVidelicet
V
11
comm='''
Junk, or working code 
that I need to comment.
'''

You can replace comm by a variable of your choice that is perhaps shorter, easy to touch-type, and you know does not (and will not) occur in your programs. Examples: xxx, oo, null, nil.

Valuate answered 7/3, 2011 at 6:12 Comment(1)
This would be loaded to memory at run time, and if the intention is to create a comment you want the program to ignore it. Leading every line with a # would be better. Also, don't assign things to a variable called null, that's just asking for disaster.Hungry
R
6

I use Notepad++ on a Windows machine, select your code, type CTRL-K. To uncomment you select code and press Ctrl + Shift + K.

Incidentally, Notepad++ works nicely as a Python editor. With auto-completion, code folding, syntax highlighting, and much more. And it's free as in speech and as in beer!

Rozanne answered 1/5, 2010 at 3:30 Comment(0)
B
6

Yes, there is (depending on your editor). In PyDev (and in Aptana Studio with PyDev):

  • Ctrl + 4 - comment selected block

  • Ctrl + 5 - uncomment selected block

Backhanded answered 25/5, 2012 at 15:41 Comment(1)
but it is not pep8 format.Wendling
C
6

In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.

Cysto answered 9/6, 2012 at 19:0 Comment(0)
P
6

In Visual Studio using the Python Tools for Visual Studio, blocks can be commented out by Ctrl+K, Ctrl+C and uncommented by Ctrl+K, Ctrl+U.

Picked answered 10/1, 2013 at 20:18 Comment(2)
This works for Visual Studio Code as well.Omora
On Windows for VS Code ctrl + /Mistreat
Z
4

The only mechanism to comment out Python code (understood as code ignored by the interpreter) is the #.

As you say, you can also use string literals, that are not ignored by the interpreter, but can be completely irrelevant for the program execution.

Zoom answered 23/3, 2009 at 22:31 Comment(0)
G
2

In Eclipse using PyDev, you can select a code block and press Ctrl + #.

Geostatics answered 13/2, 2013 at 3:20 Comment(2)
to uncomment a block, use ctrl+shift+#Barbate
This also works in komodo-edit for pythonAntitragus
P
1

Triple quotes are OK to me. You can use ''' foo ''' for docstrings and """ bar """ for comments or vice-versa to make the code more readable.

Patsypatt answered 24/3, 2009 at 7:35 Comment(1)
My problem with triple quotes is that they actually are being checked for syntax. that has to be overhead that is unneeded for a comment. Case in point: if you had ''' /NPF ''' and run that in Python 3, it will throw a syntax error. So Python 3 is checking each triple quote for syntax validity. If you switch to # and comment the line, it is skipped.Turgeon
G
1

On Eric4 there is an easy way: select a block, type Ctrl+M to comment the whole block or Ctrl+alt+M to uncomment.

Geodesic answered 18/1, 2012 at 12:20 Comment(0)
B
1

Another editor-based solution: text "rectangles" in Emacs.

Highlight the code you want to comment out, then C-x-r-t #

To un-comment the code: highlight, then C-x-r-k

I use this all-day, every day. (Assigned to hot-keys, of course.)

This and powerful regex search/replace is the reason I tolerate Emacs's other "eccentricities".

Bond answered 19/1, 2012 at 22:56 Comment(0)
M
0

Use a nice editor like SciTe, select your code, press Ctrl + Q and done.

If you don't have an editor that supports block comments you can use a triple quoted string at the start and the end of your code block to 'effectively' comment it out. It is not the best practice though.

Motorbus answered 24/3, 2009 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.