exec statement can execute code that you read, generate, or otherwise obtain during a program’s run.
exec dynamically executes a statement or a suite of statements.
exec is a simple keyword statement with the following syntax:
exec code[ in globals[,locals]]
code can be a string, an open file-like object, or a code object.
locals are dictionaries (in Python 2.4,
locals can be any mapping, but
globals must be specifically a
dict; in Python 2.5, either or both can be any mapping). If both are present, they are the global and local namespaces in which
code executes. If only
globals is present,
globals in the role of both namespaces. If neither
locals is present,
code executes in the current scope. Running
exec in the current scope is a bad idea, since it can bind, rebind, or unbind any name. To keep things under control, use
exec only with specific, explicit dictionaries.
exec only when it’s really indispensable. Most often, it’s best to avoid
exec and choose more specific, well-controlled mechanisms instead:
exec pries loose your control on your code’s namespace, damages your program’s performance, and exposes you to numerous, hard-to-find bugs.
For example, a frequently asked question about Python is “How do I set a variable whose name I just read or built?” Strictly speaking,
exec lets you do this. For example, if the name of the variable you want to set is in
varname, you might use: ...