Dynamic Execution and the exec Statement

Python’s 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. globals and 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, exec uses globals in the role of both namespaces. If neither globals nor 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.

Avoiding exec

Use 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: ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.