Julien Massardier
Julien Massardier

Reputation: 1476

Prevent Python from checking syntax errors inside an if statement whose condition isn't met

(I totally understand that return only makes sense inside functions.)

My question is: given that mylist in the following code is not None, is there a way to prevent Python from flagging the presence of return as a syntax error, and interrupting the execution?

mylist = [1,2,3]
if mylist is None: 
    return []
mylist = mylist + [4]

I'm asking this because I often run chunks of code inside a function to see what it does, step by step.

I don't mind the code execution being interrupted when the condition of the if statement is met, obviously.

But I wonder if there's a way to prevent python from checking syntax errors when they are inside an if statement whose condition is not met.

Following the advice below, I'm trying to get python to ignore the syntax error using try/except:

try:
    mylist=[1,2]
    if mylist is None:
        return []
except SyntaxError:
    pass

But the execution is still interrupted with a message about the use of return outside a function, as if the try/except was ignored.

Upvotes: 2

Views: 565

Answers (3)

Paul M.
Paul M.

Reputation: 10809

What you're asking for is impossible. Syntax errors are detected during parsing, which happens before runtime / before your code even runs, or any if-statements can be evaluated.

Upvotes: 1

ctenar
ctenar

Reputation: 808

If you want to use a chunk of code both inside and outside of a function you could use something different from 'return' to exit from the execution under a certain condition, for instance exit() or quit() or raising an Error, e.g.

def test_fct():
   list = [1,2,3]
   if list is None: 
       raise RuntimeError("Invalid value") 
   list = list + [4]

OR

def test_fct():
   list = [1,2,3]
   if list is None: 
       exit(1)
   list = list + [4]

Exit and quit internally raise a SystemExit and will terminate/restart the whole python interpreter, cf. also Python exit commands - why so many and when should each be used?

By the way, I would avoid naming a variable 'list' as this shadows the built-in type 'list'.

Upvotes: 0

furkanayd
furkanayd

Reputation: 882

By using Python Debugging (pdb) package you can debug your code. Python PDB Docs

Upvotes: 0

Related Questions