Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.5.2 console. I initially thought it was a context issue but after reading the documentation, I haven't come closer to understanding why this error ocurs.

SyntaxError: 'break' outside loop

Thanks in advance :)

EDIT: I understand that it works without exec() by the way, I'm curious why it won't work with exec (as my circumstances required it) - comprehensive answers welcome.

like image 944
Sighonide Avatar asked Nov 15 '16 14:11

Sighonide


1 Answers

This is because exec() is ignorant to your surrounding while loop. So the only statement that exec() sees in your example is break. Instead of using exec("break"), simply use break as is.

The only access the exec() function has to its surrounding scope, is the globals() and locals() dictionaries. The documentation for exec() provides some insight into how exec() works:

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). 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. The return value is None.

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

If the globals dictionary does not contain a value for the key builtins, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own builtins dictionary into globals before passing it to exec().

like image 145
Christian Dean Avatar answered Sep 18 '22 23:09

Christian Dean