Why doesn't exec(“break”) work inside a while loop

后端 未结 6 604
执笔经年
执笔经年 2021-01-18 13:26

As the question asks, why doesn\'t the below code work:

while True:
      exec(\"break\")

I am executing the above in pycharm via python 3.

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 13:49

    exec() is a function. Assuming for simplicity that a function call constitutes a statement of its own (just like in your example), it may end in one of the following ways:

    1. the function returns normally - in this case the next statement according to the control flow is executed;

    2. an exception is raised/thrown from the function - in this case the matching except clause on the call stack (if any) is executed

    3. the entire program is terminated due to an explicit call to exit() or equivalent - there is nothing to execute.

    Calling a break (as well as return or yield) from inside exec() would modify the program execution flow in a way that is incompatible with the described aspect of the function call semantics.

    Note that the documentation on exec() contains a special note on the use of return and yield inside exec():

    Be aware that the return and yield statements may not be used outside of function definitions even within the context of code passed to the exec() function.

    A similar restriction applies to the break statement (with the difference that it may not be used outside loops), and I wonder why it was not included in the documentation.

提交回复
热议问题