Re: Value of exec statements?

Guido.van.Rossum@cwi.nl
Tue, 07 Feb 1995 14:24:39 +0100

> I'm working on a project where I want to embed snippets of python code in
> a text document that will be evaluated when the document is displayed. I
> want to give the user more flexibility than is allowed with the eval
> function, but I also want a simple variable reference to return the
> variable's value like python does in interactive mode. Is there any way
> to do this with exec? To be more precise, is there any way to obtain the
> value of last python expression evaluated by exec?

There is no way to obtain the value of the last Python expression
evaluated by exec. Interactive mode does this by using a special
start symbol of the grammar, which takes either an expression or a
single statement (which may be compound, e.g. 'if', but not multiple
simple statements). Then the generated code contains "PRINT_EXPR"
instructions which print the value on stdout (unless it is None).

A trick I have used in other applications that want to behave similar
to the interpreter is the following: whenever the user submits some
code, first try if it can be parsed as an expression. If so, evaluate
the expression and print its value. If the parse fails, hide the
errors (i.e. just catch the exception) and reparse it as "exec input"
-- this will correctly parse it if it was a statement, or give the
errors when there was a syntax error.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>