Skip to content

Commit

Permalink
Patch #1550800: make exec a function.
Browse files Browse the repository at this point in the history
  • Loading branch information
birkenfeld committed Sep 6, 2006
1 parent 4e472e0 commit 7cae87c
Show file tree
Hide file tree
Showing 105 changed files with 1,221 additions and 1,558 deletions.
10 changes: 0 additions & 10 deletions Demo/parser/unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,16 +123,6 @@ def _Assert(self, t):
self.write(", ")
self.dispatch(t.msg)

def _Exec(self, t):
self.fill("exec ")
self.dispatch(t.body)
if t.globals:
self.write(" in ")
self.dispatch(t.globals)
if t.locals:
self.write(", ")
self.dispatch(t.locals)

def _Print(self, t):
self.fill("print ")
do_comma = False
Expand Down
2 changes: 1 addition & 1 deletion Demo/pysvr/pysvr.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def run_command(code, stdin, stdout, globals):
sys.stdout = sys.stderr = stdout
sys.stdin = stdin
try:
exec code in globals
exec(code, globals)
except SystemExit, how:
raise SystemExit, how, sys.exc_info()[2]
except:
Expand Down
2 changes: 1 addition & 1 deletion Demo/sockets/rpythond.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def execute(request):
sys.stdout = sys.stderr = fakefile = StringIO.StringIO()
try:
try:
exec request in {}, {}
exec(request, {}, {})
except:
print
traceback.print_exc(100)
Expand Down
6 changes: 3 additions & 3 deletions Doc/howto/doanddont.tex
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ \subsubsection{When It Is Just Fine}

\end{itemize}

\subsection{Unadorned \keyword{exec}, \function{execfile} and friends}
\subsection{Unadorned \function{exec}, \function{execfile} and friends}

The word ``unadorned'' refers to the use without an explicit dictionary,
in which case those constructs evaluate code in the {\em current} environment.
Expand All @@ -93,10 +93,10 @@ \subsection{Unadorned \keyword{exec}, \function{execfile} and friends}

\begin{verbatim}
>>> for name in sys.argv[1:]:
>>> exec "%s=1" % name
>>> exec("%s=1" % name)
>>> def func(s, **kw):
>>> for var, val in kw.items():
>>> exec "s.%s=val" % var # invalid!
>>> exec("s.%s=val" % var) # invalid!
>>> execfile("handler.py")
>>> handle()
\end{verbatim}
Expand Down
5 changes: 0 additions & 5 deletions Doc/lib/libdis.tex
Original file line number Diff line number Diff line change
Expand Up @@ -408,11 +408,6 @@ \subsection{Python Byte Code Instructions}
This opcode implements \code{from module import *}.
\end{opcodedesc}

\begin{opcodedesc}{EXEC_STMT}{}
Implements \code{exec TOS2,TOS1,TOS}. The compiler fills
missing optional parameters with \code{None}.
\end{opcodedesc}

\begin{opcodedesc}{POP_BLOCK}{}
Removes one block from the block stack. Per frame, there is a
stack of blocks, denoting nested loops, try statements, and such.
Expand Down
8 changes: 4 additions & 4 deletions Doc/lib/libexcs.tex
Original file line number Diff line number Diff line change
Expand Up @@ -293,10 +293,10 @@ \section{Built-in Exceptions}
\begin{excdesc}{SyntaxError}
% XXXJH xref to these functions?
Raised when the parser encounters a syntax error. This may occur in
an \keyword{import} statement, in an \keyword{exec} statement, in a call
to the built-in function \function{eval()} or \function{input()}, or
when reading the initial script or standard input (also
interactively).
an \keyword{import} statement, in a call to the built-in functions
\function{exec()}, \function{execfile()}, \function{eval()} or
\function{input()}, or when reading the initial script or standard
input (also interactively).

Instances of this class have attributes \member{filename},
\member{lineno}, \member{offset} and \member{text} for easier access
Expand Down
46 changes: 40 additions & 6 deletions Doc/lib/libfuncs.tex
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ \section{Built-in Functions \label{built-in-funcs}}
\begin{funcdesc}{compile}{string, filename, kind\optional{,
flags\optional{, dont_inherit}}}
Compile the \var{string} into a code object. Code objects can be
executed by an \keyword{exec} statement or evaluated by a call to
executed by a call to \function{exec()} or evaluated by a call to
\function{eval()}. The \var{filename} argument should
give the file from which the code was read; pass some recognizable value
if it wasn't read from a file (\code{'<string>'} is commonly used).
Expand Down Expand Up @@ -366,21 +366,55 @@ \section{Built-in Functions \label{built-in-funcs}}
compiled passing \code{'eval'} as the \var{kind} argument.

Hints: dynamic execution of statements is supported by the
\keyword{exec} statement. Execution of statements from a file is
\function{exec()} function. Execution of statements from a file is
supported by the \function{execfile()} function. The
\function{globals()} and \function{locals()} functions returns the
current global and local dictionary, respectively, which may be
useful to pass around for use by \function{eval()} or
\function{execfile()}.
\end{funcdesc}


\begin{funcdesc}{exec}{object\optional{, globals\optional{, locals}}}
This function supports dynamic execution of Python code.
\var{object} must be either a string, an open file object, 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). If it is an open file, the file is parsed until \EOF{} and
executed. 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 \keyword{return} and \keyword{yield} statements may
not be used outside of function definitions even within the context of
code passed to the \function{exec()} function.
The return value is \code{None}.

In all cases, if the optional parts are omitted, the code is executed
in the current scope. If only \var{globals} is provided, it must be
a dictionary, which will be used for both the global and the local
variables. If \var{globals} and \var{locals} are given, they are used
for the global and local variables, respectively. If provided,
\var{locals} can be any mapping object.

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

\note{The built-in functions \function{globals()} and \function{locals()}
return the current global and local dictionary, respectively, which
may be useful to pass around for use as the second and third
argument to \function{exec()}.}
\end{funcdesc}

\begin{funcdesc}{execfile}{filename\optional{, globals\optional{, locals}}}
This function is similar to the
\keyword{exec} statement, but parses a file instead of a string. It
This function is similar to the \function{exec()} function, but parses a
file given by the file name instead of a string. It
is different from the \keyword{import} statement in that it does not
use the module administration --- it reads the file unconditionally
and does not create a new module.\footnote{It is used relatively
rarely so does not warrant being made into a statement.}
and does not create a new module.

The arguments are a file name and two optional dictionaries. The file is
parsed and evaluated as a sequence of Python statements (similarly to a
Expand Down
4 changes: 2 additions & 2 deletions Doc/lib/libhotshot.tex
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ \subsection{Profile Objects \label{hotshot-objects}}
\end{methoddesc}

\begin{methoddesc}{run}{cmd}
Profile an \keyword{exec}-compatible string in the script environment.
Profile an \function{exec()}-compatible string in the script environment.
The globals from the \refmodule[main]{__main__} module are used as
both the globals and locals for the script.
\end{methoddesc}
Expand All @@ -76,7 +76,7 @@ \subsection{Profile Objects \label{hotshot-objects}}


\begin{methoddesc}{runctx}{cmd, globals, locals}
Evaluate an \keyword{exec}-compatible string in a specific environment.
Profile an \function{exec()}-compatible string in a specific environment.
The string is compiled before profiling begins.
\end{methoddesc}

Expand Down
5 changes: 3 additions & 2 deletions Doc/lib/libparser.tex
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,9 @@ \subsection{Converting AST Objects \label{Converting ASTs}}

\begin{funcdesc}{compileast}{ast\optional{, filename\code{ = '<ast>'}}}
The Python byte compiler can be invoked on an AST object to produce
code objects which can be used as part of an \keyword{exec} statement or
a call to the built-in \function{eval()}\bifuncindex{eval} function.
code objects which can be used as part of a call to the built-in
\function{exec()}\bifuncindex{exec} or \function{eval()}
\bifuncindex{eval} functions.
This function provides the interface to the compiler, passing the
internal parse tree from \var{ast} to the parser, using the
source file name specified by the \var{filename} parameter.
Expand Down
4 changes: 2 additions & 2 deletions Doc/lib/libpdb.tex
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ \chapter{The Python Debugger \label{debugger}}
explained below). The optional \var{globals} and \var{locals}
arguments specify the environment in which the code is executed; by
default the dictionary of the module \refmodule[main]{__main__} is
used. (See the explanation of the \keyword{exec} statement or the
\function{eval()} built-in function.)
used. (See the explanation of the built-in \function{exec()} or
\function{eval()} functions.)
\end{funcdesc}

\begin{funcdesc}{runeval}{expression\optional{, globals\optional{, locals}}}
Expand Down
6 changes: 3 additions & 3 deletions Doc/lib/libprofile.tex
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,9 @@ \section{Reference Manual -- \module{profile} and \module{cProfile}}

\begin{funcdesc}{run}{command\optional{, filename}}

This function takes a single argument that has can be passed to the
\keyword{exec} statement, and an optional file name. In all cases this
routine attempts to \keyword{exec} its first argument, and gather profiling
This function takes a single argument that can be passed to the
\function{exec()} function, and an optional file name. In all cases this
routine attempts to \function{exec()} its first argument, and gather profiling
statistics from the execution. If no file name is present, then this
function automatically prints a simple profiling report, sorted by the
standard name string (file/line/function-name) that is presented in
Expand Down
6 changes: 3 additions & 3 deletions Doc/lib/librexec.tex
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ \section{\module{rexec} ---
\end{notice}

This module contains the \class{RExec} class, which supports
\method{r_eval()}, \method{r_execfile()}, \method{r_exec()}, and
\method{r_exec()}, \method{r_eval()}, \method{r_execfile()}, and
\method{r_import()} methods, which are restricted versions of the standard
Python functions \method{eval()}, \method{execfile()} and
the \keyword{exec} and \keyword{import} statements.
Python functions \method{exec()}, \method{eval()}, \method{execfile()} and
the \keyword{import} statement.
Code executed in this restricted environment will
only have access to modules and functions that are deemed safe; you
can subclass \class{RExec} to add or remove capabilities as desired.
Expand Down
6 changes: 3 additions & 3 deletions Doc/lib/libstdtypes.tex
Original file line number Diff line number Diff line change
Expand Up @@ -1972,9 +1972,9 @@ \subsection{Code Objects \label{bltin-code-objects}}
\withsubitem{(function object attribute)}{\ttindex{func_code}}

A code object can be executed or evaluated by passing it (instead of a
source string) to the \keyword{exec} statement or the built-in
\function{eval()} function.
\stindex{exec}
source string) to the \function{exec()} or \function{eval()}
built-in functions.
\bifuncindex{exec}
\bifuncindex{eval}

See the \citetitle[../ref/ref.html]{Python Reference Manual} for more
Expand Down
2 changes: 1 addition & 1 deletion Doc/lib/libtraceback.tex
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ \subsection{Traceback Example \label{traceback-example}}
def run_user_code(envdir):
source = raw_input(">>> ")
try:
exec source in envdir
exec(source, envdir)
except:
print "Exception in user code:"
print '-'*60
Expand Down
13 changes: 6 additions & 7 deletions Doc/ref/ref2.tex
Original file line number Diff line number Diff line change
Expand Up @@ -308,13 +308,12 @@ \subsection{Keywords\label{keywords}}
\index{reserved word}

\begin{verbatim}
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
and def for is raise
as del from lambda return
assert elif global not try
break else if or while
class except import pass with
continue finally in print yield
\end{verbatim}

% When adding keywords, use reswords.py for reformatting
Expand Down
18 changes: 6 additions & 12 deletions Doc/ref/ref4.tex
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ \section{Naming and binding \label{naming}}
argument) is a code block. A script command (a command specified on
the interpreter command line with the `\strong{-c}' option) is a code
block. The file read by the built-in function \function{execfile()}
is a code block. The string argument passed to the built-in function
\function{eval()} and to the \keyword{exec} statement is a code block.
is a code block. The string argument passed to the built-in functions
\function{eval()} and \function{exec()} is a code block.
The expression read and evaluated by the built-in function
\function{input()} is a code block.

Expand Down Expand Up @@ -139,22 +139,16 @@ \subsection{Interaction with dynamic features \label{dynamic-features}}
function and the function contains or is a nested block with free
variables, the compiler will raise a \exception{SyntaxError}.

If \keyword{exec} is used in a function and the function contains or
is a nested block with free variables, the compiler will raise a
\exception{SyntaxError} unless the exec explicitly specifies the local
namespace for the \keyword{exec}. (In other words, \samp{exec obj}
would be illegal, but \samp{exec obj in ns} would be legal.)

The \function{eval()}, \function{execfile()}, and \function{input()}
functions and the \keyword{exec} statement do not have access to the
The \function{eval()}, \function{exec()}, \function{execfile()},
and \function{input()} functions do not have access to the
full environment for resolving names. Names may be resolved in the
local and global namespaces of the caller. Free variables are not
resolved in the nearest enclosing namespace, but in the global
namespace.\footnote{This limitation occurs because the code that is
executed by these operations is not available at the time the
module is compiled.}
The \keyword{exec} statement and the \function{eval()} and
\function{execfile()} functions have optional arguments to override
The \function{exec()}, \function{eval()} and \function{execfile()}
functions have optional arguments to override
the global and local namespace. If only one namespace is specified,
it is used for both.

Expand Down
65 changes: 7 additions & 58 deletions Doc/ref/ref6.tex
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ \chapter{Simple statements \label{simple}}
\productioncont{| \token{continue_stmt}}
\productioncont{| \token{import_stmt}}
\productioncont{| \token{global_stmt}}
\productioncont{| \token{exec_stmt}}
\end{productionlist}


Expand Down Expand Up @@ -809,7 +808,7 @@ \subsection{Future statements \label{future}}
That is not a future statement; it's an ordinary import statement with
no special semantics or syntax restrictions.
Code compiled by an \keyword{exec} statement or calls to the builtin functions
Code compiled by calls to the builtin functions \function{exec()},
\function{compile()} and \function{execfile()} that occur in a module
\module{M} containing a future statement will, by default, use the new
syntax or semantics associated with the future statement. This can,
Expand Down Expand Up @@ -855,64 +854,14 @@ \section{The \keyword{global} statement \label{global}}
\strong{Programmer's note:}
the \keyword{global} is a directive to the parser. It
applies only to code parsed at the same time as the \keyword{global}
statement. In particular, a \keyword{global} statement contained in an
\keyword{exec} statement does not affect the code block \emph{containing}
the \keyword{exec} statement, and code contained in an \keyword{exec}
statement is unaffected by \keyword{global} statements in the code
containing the \keyword{exec} statement. The same applies to the
statement. In particular, a \keyword{global} statement contained in a
string or code object supplied to the builtin \function{exec()} function
does not affect the code block \emph{containing} the function call,
and code contained in such a string is unaffected by \keyword{global}
statements in the code containing the function call. The same applies to the
\function{eval()}, \function{execfile()} and \function{compile()} functions.
\stindex{exec}
\bifuncindex{exec}
\bifuncindex{eval}
\bifuncindex{execfile}
\bifuncindex{compile}
\section{The \keyword{exec} statement \label{exec}}
\stindex{exec}
\begin{productionlist}
\production{exec_stmt}
{"exec" \token{expression}
["in" \token{expression} ["," \token{expression}]]}
\end{productionlist}
This statement supports dynamic execution of Python code. The first
expression should evaluate to either a string, an open file object, 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). If it is an open file, the file is parsed until \EOF{} and
executed. 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 section~\ref{file-input}, ``File input''). Be aware that
the \keyword{return} and \keyword{yield} statements may not be used
outside of function definitions even within the context of code passed
to the \keyword{exec} statement.
In all cases, if the optional parts are omitted, the code is executed
in the current scope. If only the first expression after \keyword{in}
is specified, it should be a dictionary, which will be used for both
the global and the local variables. If two expressions are given,
they are used for the global and local variables, respectively.
If provided, \var{locals} can be any mapping object.
\versionchanged[formerly \var{locals} was required to be a dictionary]{2.4}
As a side effect, an implementation may insert additional keys into
the dictionaries given besides those corresponding to variable names
set by the executed code. For example, the current implementation
may add a reference to the dictionary of the built-in module
\module{__builtin__} under the key \code{__builtins__} (!).
\ttindex{__builtins__}
\refbimodindex{__builtin__}
\strong{Programmer's hints:}
dynamic evaluation of expressions is supported by the built-in
function \function{eval()}. The built-in functions
\function{globals()} and \function{locals()} return the current global
and local dictionary, respectively, which may be useful to pass around
for use by \keyword{exec}.
\bifuncindex{eval}
\bifuncindex{globals}
\bifuncindex{locals}
2 changes: 1 addition & 1 deletion Doc/ref/ref8.tex
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ \section{File input\label{file-input}}

\item when parsing a module;

\item when parsing a string passed to the \keyword{exec} statement;
\item when parsing a string passed to the \function{exec()} function;

\end{itemize}

Expand Down
Loading

0 comments on commit 7cae87c

Please sign in to comment.