| 46 | |
| 47 | template <eval_mode mode = eval_expr> |
| 48 | object eval(const str &expr, object global = globals(), object local = object()) { |
| 49 | if (!local) { |
| 50 | local = global; |
| 51 | } |
| 52 | |
| 53 | detail::ensure_builtins_in_globals(global); |
| 54 | |
| 55 | /* PyRun_String does not accept a PyObject / encoding specifier, |
| 56 | this seems to be the only alternative */ |
| 57 | std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr; |
| 58 | |
| 59 | int start = 0; |
| 60 | switch (mode) { |
| 61 | case eval_expr: |
| 62 | start = Py_eval_input; |
| 63 | break; |
| 64 | case eval_single_statement: |
| 65 | start = Py_single_input; |
| 66 | break; |
| 67 | case eval_statements: |
| 68 | start = Py_file_input; |
| 69 | break; |
| 70 | default: |
| 71 | pybind11_fail("invalid evaluation mode"); |
| 72 | } |
| 73 | |
| 74 | PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr()); |
| 75 | if (!result) { |
| 76 | throw error_already_set(); |
| 77 | } |
| 78 | return reinterpret_steal<object>(result); |
| 79 | } |
| 80 | |
| 81 | template <eval_mode mode = eval_expr, size_t N> |
| 82 | object eval(const char (&s)[N], object global = globals(), object local = object()) { |