7
votes

In python to comment-out multiple lines we use triple quotes

def x():
   """This code will 
      add 1 and 1 """
   a=1+1

but what if I have to comment out a block of code which already contains lot of other comment out blocks (triple quote comments). For example if I want to comment out this function fully..

"""
def x():
   """This code will 
      add 1 and 1 """
   a=1+1
"""

This doesn't work. How can I comment out such blocks of code.

4
If you have double quotes on the inside, you can use single quotes on the outside. ''' """comment""" '''. this works.Josiah

4 Answers

13
votes

In python to comment-out multiple lines we use triple commas

That’s just one way of doing it, and you’re technically using a string literal, not a comment. And, although it has become fairly established, this way of writing comments has the drawback you observed: you cannot comment out nested blocks.1

Python doesn’t have nesting multiline comments, it’s as simple as that. If you want to comment out multiple lines allowing for nested comments, the only safe choice is to comment out each line.

Most editors have some command that makes commenting out or in multiple lines easy.


1 For a single level of nesting you can in fact use '''"""nested """''', or the other way round. But I wouldn’t recommend it.

5
votes

What I often do in brief hack&slay situations is something like this below. It is not really a comment, and it does not cover all cases (because you need to have a block), but maybe it is helpful:

if 0:  # disabled because *some convincing reason*
  def x():
   """This code will 
      add 1 and 1 """
   a=1+1

Or, if you cannot or don't like to introduce indenting levels between the typical ones:

# disabled because *some convincing reason*
if 0:  # def x():
   """This code will 
      add 1 and 1 """
   a=1+1
0
votes

You should use # for commenting, and at the beginning of each line. This is very easy if you're using eclipse + pydev.

Simply select the block of code to comment, and press Ctrl + \. The same goes for uncommentng as well.

I'm sure there are such easy ways in other editors as well.

-1
votes

I'm taking a Udacity python programming course building a search engine. They use the triple quotes to enclose a webpage's source code as a string in the variable 'page' to be searched for all the links.

page = '''web page source code''' that is searched with a page.find()