How to process syntax errors

Steve D'Aprano steve+python at pearwood.info
Tue Oct 11 13:12:05 EDT 2016


On Tue, 11 Oct 2016 03:58 pm, Terry Reedy wrote:

> On 10/10/2016 11:24 AM, Chris Angelico wrote:
>> On Tue, Oct 11, 2016 at 1:13 AM,  <mr.puneet.goyal at gmail.com> wrote:
>>> Is there any way to capture syntax errors and process them ? I want to
>>> write a function which calls every time whenever there is syntax error
>>> in the program.
> 
>> However, you can catch this at some form of outer level. If you're
>> using exec/eval to run the code, you can guard that:
>>
>> code = """
>> obj = MyClass() # using PEP 8 names
>> obj xyz
>> """
>> try:
>>     exec(code)
>> except SyntaxError:
>>     print("Blah blah blah")
> 
> Far from being 'un-pythonic' (Puneet's response), this is essentially
> what the interpreter does, either without or with a separate explicit
> compile step.

There is a *huge* difference between writing an interpreter which takes
source code written in idiomatic Python:

# source code looks like this
x = [1, 2]
y = len(x)
print(y + 1)


reading that source code into a string (either all at once, or a line at a
time), then using exec() to execute the string:

try:
    exec(source_code)
except SyntaxError:
    # emit error


and what I believe the OP wishes to do, which is to put the entire source
code inside a call to exec:

# source code looks like this:
try:
    text = """\
x = [1, 2]
y = len(x)
print(y + 1)
"""
    exec(text)
except SyntaxError:
    # recover from syntax error somehow, and keep processing


What the OP appears to want is not to write Python code at all, but to write
something where function calls are delimited with spaces:

# source code looks like this:
try:
    text = """\
x = [1, 2]
y = len x
print y + 1
"""
    exec(text)
except SyntaxError:
    # automatically re-format the syntax errors into legal 
    # Python code and execute again


See the OP's thread with subject 

"A newbie doubt on methods/functions calling"

from last week. I believe that he hasn't given up on the hope to avoid
writing parentheses and just use spaces, even though we've already
explained that is ambiguous:

func a b c
# is that func(a, b, c) or func(a(b, c)) or func(a, b(c)) or ... ?

I don't believe that mr.puneet.goyal is planning to write an interpreter for
Python. I believe that he's hoping to find some trick or hack so he can
avoid parentheses for function calls, and he hopes that by catching
SyntaxError he can do this.


But I could be wrong... 



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list