Tim Clemans
Tim Clemans

Reputation: 935

How do I get more informative Python syntax errors

I am teaching someone Python. This person executed below

if 2 == 2
    print 'hi'

which gave

    if 2 == 2
            ^
SyntaxError: invalid syntax

Is there a way to get Python to say missing : at end of if statement?

Upvotes: 0

Views: 173

Answers (1)

Rory Daulton
Rory Daulton

Reputation: 22564

The only way to get that kind of helpful detail in error messages is to use (or write your own) interpreter/compiler that does so.

Figuring out the exact cause of a syntax error is difficult, and an interpreter or compiler that can usually do so is difficult to write and has a much larger footprint in both memory and in compile/interpret/run time.

When I was in college I learned PL/C, which is a compatible variant of PL/I that does what you want. In fact, it attempted to correct the syntax error and keep compiling the program. Run-time errors were also corrected, as much as possible. The philosophy was to give the programmer as much debug information as possible on each compile or run. That language was only used for development: once a program is debugged, PL/I compiles and runs the program much more quickly. I have never seen the equivalent for Python, but I see no theoretical reason why it could not be done. That seems to be a good topic for PhD dissertation!

Upvotes: 5

Related Questions