1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use crate::run::run_python_code;
use crate::PythonBlock;
use pyo3::{ffi, types::PyDict, AsPyPointer, AsPyRef, FromPyObject, Py, PyErr, PyResult, Python, ToPyObject};
pub struct Context {
pub(crate) globals: Py<PyDict>,
}
impl Context {
pub fn new() -> Self {
Self::new_with_gil(Python::acquire_gil().python())
}
pub fn new_with_gil(py: Python) -> Self {
match Self::try_new(py) {
Ok(x) => x,
Err(error) => {
error.print(py);
panic!("failed to create Python context");
}
}
}
fn try_new(py: Python) -> PyResult<Self> {
let main_mod = unsafe { ffi::PyImport_AddModule("__main__\0".as_ptr() as *const _) };
if main_mod.is_null() {
return Err(PyErr::fetch(py));
};
let globals = PyDict::new(py);
if unsafe { ffi::PyDict_Merge(globals.as_ptr(), ffi::PyModule_GetDict(main_mod), 0) != 0 } {
return Err(PyErr::fetch(py));
}
Ok(Self { globals: globals.into() })
}
pub fn globals<'p>(&'p self, py: Python<'p>) -> &'p PyDict {
self.globals.as_ref(py)
}
pub fn get<T: for<'p> FromPyObject<'p>>(&self, name: &str) -> T {
self.get_with_gil(Python::acquire_gil().python(), name)
}
pub fn get_with_gil<'p, T: FromPyObject<'p>>(&'p self, py: Python<'p>, name: &str) -> T {
match self.globals(py).get_item(name) {
None => panic!("Python context does not contain a variable named `{}`", name),
Some(value) => match FromPyObject::extract(value) {
Ok(value) => value,
Err(e) => {
e.print(py);
panic!("Unable to convert `{}` to `{}`", name, std::any::type_name::<T>());
}
},
}
}
pub fn set<T: ToPyObject>(&self, name: &str, value: T) {
self.set_with_gil(Python::acquire_gil().python(), name, value)
}
pub fn set_with_gil<'p, T: ToPyObject>(&self, py: Python<'p>, name: &str, value: T) {
match self.globals(py).set_item(name, value) {
Ok(()) => (),
Err(e) => {
e.print(py);
panic!("Unable to set `{}` from a `{}`", name, std::any::type_name::<T>());
}
}
}
pub fn run<F: FnOnce(&PyDict)>(&self, code: PythonBlock<F>) {
self.run_with_gil(Python::acquire_gil().python(), code);
}
pub fn run_with_gil<'p, F: FnOnce(&PyDict)>(&self, py: Python<'p>, code: PythonBlock<F>) {
(code.set_variables)(self.globals(py));
match run_python_code(py, self, code.bytecode) {
Ok(_) => (),
Err(e) => {
e.print(py);
panic!("python!{...} failed to execute");
}
}
}
}