Skip to content

Commit b130c93

Browse files
committed
Backport new eval() function from HEAD.
[SVN r37693]
1 parent 13432b5 commit b130c93

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

include/boost/python/exec.hpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,25 @@ namespace boost
1313
namespace python
1414
{
1515

16+
// Evaluate python expression from str.
17+
// global and local are the global and local scopes respectively,
18+
// used during evaluation.
19+
object
20+
BOOST_PYTHON_DECL
21+
eval(str string, object global = object(), object local = object());
22+
1623
// Execute python source code from str.
1724
// global and local are the global and local scopes respectively,
1825
// used during execution.
1926
object
20-
BOOST_PYTHON_DECL
27+
BOOST_PYTHON_DECL
2128
exec(str string, object global = object(), object local = object());
2229

2330
// Execute python source code from file filename.
2431
// global and local are the global and local scopes respectively,
2532
// used during execution.
2633
object
27-
BOOST_PYTHON_DECL
34+
BOOST_PYTHON_DECL
2835
exec_file(str filename, object global = object(), object local = object());
2936

3037
}

src/exec.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@ namespace boost
1313
namespace python
1414
{
1515

16+
object BOOST_PYTHON_DECL eval(str string, object global, object local)
17+
{
18+
// should be 'char const *' but older python versions don't use 'const' yet.
19+
char *s = python::extract<char *>(string);
20+
PyObject* result = PyRun_String(s, Py_eval_input, global.ptr(), local.ptr());
21+
if (!result) throw_error_already_set();
22+
return object(detail::new_reference(result));
23+
}
24+
1625
object BOOST_PYTHON_DECL exec(str string, object global, object local)
1726
{
1827
// should be 'char const *' but older python versions don't use 'const' yet.

test/exec.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,13 @@ BOOST_PYTHON_MODULE(embedded_hello)
4949
}
5050

5151

52+
void eval_test()
53+
{
54+
python::object result = python::eval("'abcdefg'.upper()");
55+
std::string value = python::extract<std::string>(result) BOOST_EXTRACT_WORKAROUND;
56+
BOOST_TEST(value == "ABCDEFG");
57+
}
58+
5259
void exec_test()
5360
{
5461
// Register the module with the interpreter
@@ -108,7 +115,8 @@ int main(int argc, char **argv)
108115
// Initialize the interpreter
109116
Py_Initialize();
110117

111-
if (python::handle_exception(exec_test) ||
118+
if (python::handle_exception(eval_test) ||
119+
python::handle_exception(exec_test) ||
112120
python::handle_exception(boost::bind(exec_file_test, script)))
113121
{
114122
if (PyErr_Occurred())

0 commit comments

Comments
 (0)