[C++-sig] Re: [BPL] python::interpreter proposal

Bjorn Pettersen BPettersen at NAREX.com
Thu Jan 2 19:56:57 CET 2003

> From: Dirk Gerrits [mailto:dirk at gerrits.homeip.net] 
> Nicodemus wrote:
> > I think two separate functions would be better.
> > 
> > void interpreter::exec( const std::string& code, dict& globals,
dict& locals );
> > - Executes the given code in the context of the two given
> > 
> > object interpreter::eval( const std::string& expr, dict& globals,
dict& locals );
> > - Evaluates the Python expression given, in the context of the two 
> > dictionaries, and returns the resulting object.
> > 
> > They're equivalent to the "exec" statement and to the "eval" builtin
> > function in python.
> I like that. Let's hear what others think about it.

That's essentially what I ended up with, although I have the
global/local dict be persistent with the interpreter (i.e. you don't
pass them in). Making them optional would probably be most

I ended up making exec return an int so that we could do:

  int foo(int x) {
      static int ok = py::exec(
          "def foo(y):\n"
          "    return y**y\n");
      return py::extract<int>(py::fn("foo")(x));

(i.e. only calling exec once).

In addition to exec/eval I also have an "execute block" function that
takes a series of statements, executes them, and returns the value of
the last statement. It's convenient because we normally want to execute
a "script" to get a result and the script normally consists of multiple
lines. I implemented that by extracting the last statement, passing
everything prior to it to exec, and returning the result of passing the
last statement to eval. Of course, extracting the last statement is
non-trivial and my implementation is wrong, although it does work for
most cases <wink>.

-- bjorn

More information about the Cplusplus-sig mailing list