Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comment out nested triple quotes

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.

like image 813
d.putto Avatar asked May 21 '12 09:05

d.putto


People also ask

What is a comment enclosed within triple quotes known as?

Note: Triple quotes, according to official Python documentation are docstrings, or multi-line docstrings and are not considered comments. Anything inside triple quotes is read by the interpreter. When the interpreter encounters the hash symbol, it ignores everything after that. That is what a comment is defined to be.

Can you write multi-line comments in Python using triple quotes either or?

Python only has one way of doing comments and that is using # . Triple quotes are treated as regular strings with the exception that they can span multiple lines.

How do you comment on multiple lines?

To comment out multiple lines in Python, you can prepend each line with a hash ( # ). With this approach, you're technically making multiple single-line comments. The real workaround for making multi-line comments in Python is by using docstrings.

How do you escape triple quotes in Python?

Escaping the quote characters with a backslash always works.


1 Answers

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.

like image 84
Konrad Rudolph Avatar answered Sep 29 '22 13:09

Konrad Rudolph