Search code examples
pythonpython-3.xsyntax-errorindentation

Why are "Missing parentheses in call to 'print'" reported as an IndentationError rather than a SyntaxError?


In Python 3.5.2 and Python 3.6.1, when I try this code:

if True:
print "just right!"

I get an error like:

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

This happens both at the REPL and when running the code from a .py file.

According to What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python? , it seems like the error should be reported as a SyntaxError, not as an IndentationError. As explained in the top answer there:

“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.

That matches the error message I got, but not the exception type.

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


Solution

  • 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.