d.putto d.putto - 4 months ago 12
Python Question

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.

Answer

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.