Chapter 13. Controlling Execution
Python directly exposes many of the mechanisms it uses internally.
This helps you understand Python at an advanced level, and means you
can hook your own code into such documented Python mechanisms and
control those mechanisms to some extent. For example, Chapter 7 covered the
statement and the way Python arranges for built-ins to be made
implicitly visible. This chapter covers other advanced techniques
that Python offers for controlling execution, while Chapter 17 covers execution-control possibilities that
apply specifically to the three crucial phases of development:
testing, debugging, and profiling.
Dynamic Execution and the exec Statement
exec statement, it is possible to execute code
that you read, generate, or otherwise obtain during the running of a
exec statement dynamically executes a
statement or a suite of statements.
exec is a
simple keyword statement with the following syntax:
code can be a string, an open file-like
object, or a code object.
locals are dictionaries. If both are
present, they are the global and local namespaces, respectively, in
code executes. If only
globals is present,
the role of both namespaces. If neither
locals is present,
code executes in the current scope.
exec in current scope is not good programming practice, since it can bind, rebind, or unbind any name. To keep things under control, ...