Advertisement
Advertisement


How to comment out a block of code in Python


Question

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

2018/11/06
1
483
11/6/2018 9:06:20 PM

Accepted Answer

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

2013/08/13
434
8/13/2013 1:42:16 PM

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

2009/03/23

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

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

or:

if False: '''
...statements...
'''
2009/03/24

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.

2014/03/19

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

2013/10/01

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

2014/03/19

Source: https://stackoverflow.com/questions/675442
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]