且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

确实返回停止一个python脚本

更新时间:2023-12-04 23:16:58

  1. 不会执行打印语句.
  2. 该计划不会终止.

函数将返回,并且执行将在栈上的下一帧继续.在 C 中,程序的入口点是一个名为 main 的函数.如果您从该函数return,程序本身将终止.然而,在 Python 中,main 在程序代码中被显式调用,因此 return 语句本身不会退出程序.

您示例中的 print 语句就是我们所说的 死代码.死代码是永远无法执行的代码.if False: print 'hi' 中的 print 语句是死代码的另一个例子.许多编程语言提供死代码消除或 DCE,它在编译时去除这些语句.Python 的 AST 编译器显然具有 DCE,但不能保证所有代码对象都具有 DCE.如果应用 DCE,以下两个函数将编译为相同的字节码:

def f():返回 1打印嗨"定义 g():返回 1

但根据 CPython 反汇编器,DCE 不适用:

>>>dis.dis(f)2 0 LOAD_CONST 1 (1)3 RETURN_VALUE3 4 LOAD_CONST 2 ('嗨')7 PRINT_ITEM8 PRINT_NEWLINE>>>dis.dis(g)2 0 LOAD_CONST 1 (1)3 RETURN_VALUE

def foo:
    return 1
    print(varsum)

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

  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