does return stop a python script

Hans picture Hans · May 19, 2014 · Viewed 20.5k times · Source
def foo:
    return 1
    print(varsum)

would the print command still be executed, or would the program be terminated at return()

Answer

kojiro picture kojiro · May 19, 2014
  1. The print statement would not be executed.
  2. The program would not be terminated.

The function would return, and execution would continue at the next frame up the stack. In C the entry point of the program is a function called main. If you return from that function, the program itself terminates. In Python, however, main is called explicitly within the program code, so the return statement itself does not exit the program.

The print statement in your example is what we call dead code. Dead code is code that cannot ever be executed. The print statement in if False: print 'hi' is another example of dead code. Many programming languages provide dead code elimination, or DCE, that strips out such statements at compile time. Python apparently has DCE for its AST compiler, but it is not guaranteed for all code objects. The following two functions would compile to identical bytecode if DCE were applied:

def f():
    return 1
    print 'hi'
def g():
    return 1

But according to the CPython disassembler, DCE is not applied:

>>> dis.dis(f)
  2           0 LOAD_CONST               1 (1)
              3 RETURN_VALUE        

  3           4 LOAD_CONST               2 ('hi')
              7 PRINT_ITEM          
              8 PRINT_NEWLINE       
>>> dis.dis(g)
  2           0 LOAD_CONST               1 (1)
              3 RETURN_VALUE