2

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

Julien Massardier
  • 1,326
  • 1
  • 11
  • 29
  • 1
    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. – Paul M. Nov 25 '19 at 17:46
  • Aight, it's what I suspected, thanks. Do you want to post this as an answer so I can give you credit? – Julien Massardier Nov 28 '19 at 08:52

3 Answers3

1

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.

Paul M.
  • 10,481
  • 2
  • 9
  • 15
0

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

furkanayd
  • 811
  • 7
  • 19
0

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

ctenar
  • 718
  • 5
  • 24