Unable to comment out code involving multiline strings

2020-05-23 python

Basically I am curious about why this throws a syntax error and what is the pythonic way to 'comment out' portions of my code that I am not using, for example during a debugging session.

'''
def foo():
        '''does nothing'''
'''

Answers

You can use triple double quotes to comment out triple single quotes:

"""
def foo():
    '''does nothing'''
"""

Python is interpreting your code like this:

First comment:

'''
def foo():
        '''

Second comment:

    '''
'''

Therefore, the "does nothing" is outside the comment, and python tries to interpret it, but the syntax is invalid, so it gives an error.

The Pythonic way is to understand the difference between a multi-line string and a comment and use them appropriately.

Python does not have multi-line comments, but many python aware editors and IDE's have ways to automatically comment out selected multiple lines, (and the reverse). You might want to search for that useful functionality.

Related