The Python Oracle

How to comment out a block of code in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping

--

Chapters
00:00 Question
00:40 Accepted answer (Score 479)
01:25 Answer 2 (Score 101)
01:43 Answer 3 (Score 99)
01:58 Answer 4 (Score 46)
02:35 Thank you

--

Full question
https://stackoverflow.com/questions/6754...

Accepted answer links:
[PEP 8]: http://www.python.org/dev/peps/pep-0008/

Answer 4 links:
[vi]: http://en.wikipedia.org/wiki/Vi
[Emacs]: http://en.wikipedia.org/wiki/Emacs

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #docstring

#avk47



ACCEPTED ANSWER

Score 485


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.




ANSWER 2

Score 106


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

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

or:

if False: '''
...statements...
'''



ANSWER 3

Score 99


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




ANSWER 4

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