μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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
21inline void ensure_builtins_in_globals(object &global) {
22#if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x03080000
23 // Running exec and eval on Python 2 and 3 adds `builtins` module under
24 // `__builtins__` key to globals if not yet present.
25 // Python 3.8 made PyRun_String behave similarly. Let's also do that for
26 // older versions, for consistency. This 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
39
42
45};
46
47template <eval_mode mode = eval_expr>
48object 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;
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
81template <eval_mode mode = eval_expr, size_t N>
82object 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
88inline void exec(const str &expr, object global = globals(), object local = object()) {
89 eval<eval_statements>(expr, std::move(global), std::move(local));
90}
91
92template <size_t N>
93void 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) && PY_VERSION_HEX >= 0x03000000
98template <eval_mode mode = eval_statements>
99object eval_file(str, object, object) {
100 pybind11_fail("eval_file not supported in PyPy3. Use eval");
101}
102template <eval_mode mode = eval_statements>
103object eval_file(str, object) {
104 pybind11_fail("eval_file not supported in PyPy3. Use eval");
105}
106template <eval_mode mode = eval_statements>
107object eval_file(str) {
108 pybind11_fail("eval_file not supported in PyPy3. Use eval");
109}
110#else
111template <eval_mode mode = eval_statements>
112object eval_file(str fname, object global = globals(), object local = object()) {
113 if (!local) {
114 local = global;
115 }
116
117 detail::ensure_builtins_in_globals(global);
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# if PY_VERSION_HEX >= 0x03040000
137 FILE *f = _Py_fopen_obj(fname.ptr(), "r");
138# elif PY_VERSION_HEX >= 0x03000000
139 FILE *f = _Py_fopen(fname.ptr(), "r");
140# else
141 /* No unicode support in open() :( */
142 auto fobj = reinterpret_steal<object>(
143 PyFile_FromString(const_cast<char *>(fname_str.c_str()), const_cast<char *>("r")));
144 FILE *f = nullptr;
145 if (fobj)
146 f = PyFile_AsFile(fobj.ptr());
147 closeFile = 0;
148# endif
149 if (!f) {
150 PyErr_Clear();
151 pybind11_fail("File \"" + fname_str + "\" could not be opened!");
152 }
153
154 // In Python2, this should be encoded by getfilesystemencoding.
155 // We don't boher setting it since Python2 is past EOL anyway.
156 // See PR#3233
157# if PY_VERSION_HEX >= 0x03000000
158 if (!global.contains("__file__")) {
159 global["__file__"] = std::move(fname);
160 }
161# endif
162
163# if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION)
164 PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), local.ptr());
165 (void) closeFile;
166# else
167 PyObject *result
168 = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);
169# endif
170
171 if (!result) {
172 throw error_already_set();
173 }
174 return reinterpret_steal<object>(result);
175}
176#endif
177
Fetch and hold an error which was already set in Python.
Definition: pytypes.h:379
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:203
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:1200
Definition: pytypes.h:1200
dict globals()
Return a dictionary representing the global variables in the current execution frame,...
Definition: pybind11.h:1288
PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Thrown when pybind11::cast or.
Definition: common.h:992
#define PYBIND11_BUILTINS_MODULE
Definition: common.h:323
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:21
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:20
eval_mode
Definition: eval.h:36
@ eval_expr
Evaluate a string containing an isolated expression.
Definition: eval.h:38
@ eval_statements
Evaluate a string containing a sequence of statement. Returns none.
Definition: eval.h:44
@ eval_single_statement
Evaluate a string containing a single statement. Returns none.
Definition: eval.h:41
void ensure_builtins_in_globals(object &global)
Definition: eval.h:21
object eval(const str &expr, object global=globals(), object local=object())
Definition: eval.h:48
void exec(const str &expr, object global=globals(), object local=object())
Definition: eval.h:88
object eval_file(str fname, object global=globals(), object local=object())
Definition: eval.h:112