Mr Mystery Guest
Mr Mystery Guest

Reputation: 1484

Commented block indentation in python

Is there a way to avoid "expected indent block" errors in Python without adding pass to a function?

def exclamation(s):
 # s += "!!!"
 # return s

print exclamation("The indented horror")

The above code results in an error on line 5. Yes, remove the comments and the code works fine. However, in debugging stuff I often find myself in a similar situation. Is this just a hang-up of the off-side rule and something I need to get used to or are there ways around this?

Upvotes: 1

Views: 65

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53718

There has to be something within your function definition to avoid a SyntaxError.

The issue is that the interpreter will effectively ignore comments during parsing, and so while to a human it might look like something is there, to the parser it is empty.

As jonrsharpe has pointed out in a comment, you can use docstrings to "comment out" your code and have it still work. This is because the docstring is, in effect, a normal string. As such this will be parsed and won't cause a SyntaxError. To take your example code it would look like:

def exclamation(s):
  '''s += "!!!"
  return s'''

# This should print None as nothing is now returned from the func
print(exclamation("The indented horror"))

Upvotes: 3

Related Questions