6

Why in the following program is an IndentationError being raised rather than SyntaxError?

>>> if True:
... print "just right!"
  File "<stdin>", line 2
    print "just right!"
        ^
IndentationError: Missing parentheses in call to 'print'

To make sure the IDLE wasn't just acting funny, I also tested this code by running it from a normal source file. The same exception type is still being raised. The versions of Python I used to test this were Python 3.5.2 and Python 3.6.1.

It is my understanding that missing parenthesis when using print was considered a SyntaxError, not an IndentationError. The top answer in the post What does “SyntaxError: Missing parentheses in call to 'print'” mean in Python? also seems to support this:

“SyntaxError: Missing parentheses in call to 'print'” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.

Is this a bug? If so, what's causing it?

Christian Dean
  • 22,138
  • 7
  • 54
  • 87

1 Answers1

7

IndentationError is a subclass of SyntaxError, so technically, this is a syntax error being raised.

You have two errors here. Both the indentation is wrong and you are missing parentheses. It's a bit of a bug, there is code that alters the SyntaxError message when the print special case is detected, and that code still applies for subclasses of SyntaxError (it is applied in the SyntaxError exception constructor).

You can trigger the same error for the TabError exception:

>>> compile('if 1:\n    1\n\tprint "Look ma, tabs!"', '', 'single')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "", line 3
    print "Look ma, tabs!"
                         ^
TabError: Missing parentheses in call to 'print'

The SyntaxError codepath checking for the exec() and print() edge-cases should really only fire for actual SyntaxError instances, not subclasses, as that's just confusing.

I've filed issue 31161 to track this.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343