eval.h
Go to the documentation of this file.
1 /*
2  pybind11/eval.h: Support for evaluating Python expressions and statements
3  from strings and files
4 
5  Copyright (c) 2016 Klemens Morgenstern <klemens.morgenstern@ed-chemnitz.de> and
6  Wenzel Jakob <wenzel.jakob@epfl.ch>
7 
8  All rights reserved. Use of this source code is governed by a
9  BSD-style license that can be found in the LICENSE file.
10 */
11 
12 #pragma once
13 
14 #include "pybind11.h"
15 
16 #include <utility>
17 
20 
21 inline void ensure_builtins_in_globals(object &global) {
22 #if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x03080000
23  // Running exec and eval adds `builtins` module under `__builtins__` key to
24  // globals if not yet present. Python 3.8 made PyRun_String behave
25  // similarly. Let's also do that for older versions, for consistency. This
26  // was missing from PyPy3.8 7.3.7.
27  if (!global.contains("__builtins__"))
28  global["__builtins__"] = module_::import(PYBIND11_BUILTINS_MODULE);
29 #else
30  (void) global;
31 #endif
32 }
33 
35 
36 enum eval_mode {
39 
42 
45 };
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 
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;
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()) {
83  /* Support raw string literals by removing common leading whitespace */
84  auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s)) : str(s);
85  return eval<mode>(expr, std::move(global), std::move(local));
86 }
87 
88 inline void exec(const str &expr, object global = globals(), object local = object()) {
89  eval<eval_statements>(expr, std::move(global), std::move(local));
90 }
91 
92 template <size_t N>
93 void exec(const char (&s)[N], object global = globals(), object local = object()) {
94  eval<eval_statements>(s, std::move(global), std::move(local));
95 }
96 
97 #if defined(PYPY_VERSION)
98 template <eval_mode mode = eval_statements>
99 object eval_file(str, object, object) {
100  pybind11_fail("eval_file not supported in PyPy3. Use eval");
101 }
102 template <eval_mode mode = eval_statements>
103 object eval_file(str, object) {
104  pybind11_fail("eval_file not supported in PyPy3. Use eval");
105 }
106 template <eval_mode mode = eval_statements>
107 object eval_file(str) {
108  pybind11_fail("eval_file not supported in PyPy3. Use eval");
109 }
110 #else
111 template <eval_mode mode = eval_statements>
112 object eval_file(str fname, object global = globals(), object local = object()) {
113  if (!local) {
114  local = global;
115  }
116 
118 
119  int start = 0;
120  switch (mode) {
121  case eval_expr:
122  start = Py_eval_input;
123  break;
125  start = Py_single_input;
126  break;
127  case eval_statements:
128  start = Py_file_input;
129  break;
130  default:
131  pybind11_fail("invalid evaluation mode");
132  }
133 
134  int closeFile = 1;
135  std::string fname_str = (std::string) fname;
136  FILE *f = _Py_fopen_obj(fname.ptr(), "r");
137  if (!f) {
138  PyErr_Clear();
139  pybind11_fail("File \"" + fname_str + "\" could not be opened!");
140  }
141 
142  if (!global.contains("__file__")) {
143  global["__file__"] = std::move(fname);
144  }
145 
146  PyObject *result
147  = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);
148 
149  if (!result) {
150  throw error_already_set();
151  }
152  return reinterpret_steal<object>(result);
153 }
154 #endif
155 
module_::import
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:1211
error_already_set
Definition: pytypes.h:722
s
RealScalar s
Definition: level1_cplx_impl.h:126
eval_single_statement
@ eval_single_statement
Evaluate a string containing a single statement. Returns none.
Definition: eval.h:41
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
eval_statements
@ eval_statements
Evaluate a string containing a sequence of statement. Returns none.
Definition: eval.h:44
detail
Definition: testSerializationNonlinear.cpp:70
buffer
Definition: pytypes.h:2223
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
eval
object eval(const str &expr, object global=globals(), object local=object())
Definition: eval.h:48
result
Values result
Definition: OdometryOptimize.cpp:8
ensure_builtins_in_globals
void ensure_builtins_in_globals(object &global)
Definition: eval.h:21
eval_mode
eval_mode
Definition: eval.h:36
exec
void exec(const str &expr, object global=globals(), object local=object())
Definition: eval.h:88
eval_expr
@ eval_expr
Evaluate a string containing an isolated expression.
Definition: eval.h:38
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1013
str
Definition: pytypes.h:1524
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
pybind11.h
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:241
eval_file
object eval_file(str fname, object global=globals(), object local=object())
Definition: eval.h:112
mode
static const DiscreteKey mode(modeKey, 2)
N
#define N
Definition: igam.h:9
globals
dict globals()
Definition: pybind11.h:1287
PYBIND11_BUILTINS_MODULE
#define PYBIND11_BUILTINS_MODULE
Definition: wrap/pybind11/include/pybind11/detail/common.h:366
gtsam.examples.ShonanAveragingCLI.str
str
Definition: ShonanAveragingCLI.py:115


gtsam
Author(s):
autogenerated on Thu Jun 13 2024 03:02:19