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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use crate::err::{PyErr, PyResult};
use crate::exceptions;
use crate::ffi;
use crate::instance::PyNativeType;
use crate::object::PyObject;
use crate::pyclass::PyClass;
use crate::type_object::PyTypeObject;
use crate::types::PyTuple;
use crate::types::{PyAny, PyDict, PyList};
use crate::{AsPyPointer, IntoPy, Py, Python, ToPyObject};
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::str;
#[repr(transparent)]
pub struct PyModule(PyAny);
pyobject_native_var_type!(PyModule, ffi::PyModule_Type, ffi::PyModule_Check);
impl PyModule {
pub fn new<'p>(py: Python<'p>, name: &str) -> PyResult<&'p PyModule> {
let name = CString::new(name)?;
unsafe { py.from_owned_ptr_or_err(ffi::PyModule_New(name.as_ptr())) }
}
pub fn import<'p>(py: Python<'p>, name: &str) -> PyResult<&'p PyModule> {
let name = CString::new(name)?;
unsafe { py.from_owned_ptr_or_err(ffi::PyImport_ImportModule(name.as_ptr())) }
}
pub fn from_code<'p>(
py: Python<'p>,
code: &str,
file_name: &str,
module_name: &str,
) -> PyResult<&'p PyModule> {
let data = CString::new(code)?;
let filename = CString::new(file_name)?;
let module = CString::new(module_name)?;
unsafe {
let cptr = ffi::Py_CompileString(data.as_ptr(), filename.as_ptr(), ffi::Py_file_input);
if cptr.is_null() {
return Err(PyErr::fetch(py));
}
let mptr = ffi::PyImport_ExecCodeModuleEx(module.as_ptr(), cptr, filename.as_ptr());
if mptr.is_null() {
return Err(PyErr::fetch(py));
}
<&PyModule as crate::FromPyObject>::extract(py.from_owned_ptr_or_err(mptr)?)
}
}
pub fn dict(&self) -> &PyDict {
unsafe {
let ptr = ffi::PyModule_GetDict(self.as_ptr());
ffi::Py_INCREF(ptr);
self.py().from_owned_ptr(ptr)
}
}
pub fn index(&self) -> PyResult<&PyList> {
match self.getattr("__all__") {
Ok(idx) => idx.downcast().map_err(PyErr::from),
Err(err) => {
if err.is_instance::<exceptions::AttributeError>(self.py()) {
let l = PyList::empty(self.py());
self.setattr("__all__", l).map_err(PyErr::from)?;
Ok(l)
} else {
Err(err)
}
}
}
}
unsafe fn str_from_ptr(&self, ptr: *const c_char) -> PyResult<&str> {
if ptr.is_null() {
Err(PyErr::fetch(self.py()))
} else {
let slice = CStr::from_ptr(ptr).to_bytes();
match str::from_utf8(slice) {
Ok(s) => Ok(s),
Err(e) => Err(PyErr::from_instance(
exceptions::UnicodeDecodeError::new_utf8(self.py(), slice, e)?,
)),
}
}
}
pub fn name(&self) -> PyResult<&str> {
unsafe { self.str_from_ptr(ffi::PyModule_GetName(self.as_ptr())) }
}
pub fn filename(&self) -> PyResult<&str> {
unsafe { self.str_from_ptr(ffi::PyModule_GetFilename(self.as_ptr())) }
}
pub fn call(
&self,
name: &str,
args: impl IntoPy<Py<PyTuple>>,
kwargs: Option<&PyDict>,
) -> PyResult<&PyAny> {
self.getattr(name)?.call(args, kwargs)
}
pub fn call1(&self, name: &str, args: impl IntoPy<Py<PyTuple>>) -> PyResult<&PyAny> {
self.getattr(name)?.call1(args)
}
pub fn call0(&self, name: &str) -> PyResult<&PyAny> {
self.getattr(name)?.call0()
}
pub fn get(&self, name: &str) -> PyResult<&PyAny> {
self.getattr(name)
}
pub fn add<V>(&self, name: &str, value: V) -> PyResult<()>
where
V: ToPyObject,
{
self.index()?
.append(name)
.expect("could not append __name__ to __all__");
self.setattr(name, value)
}
pub fn add_class<T>(&self) -> PyResult<()>
where
T: PyClass,
{
self.add(T::NAME, <T as PyTypeObject>::type_object(self.py()))
}
pub fn add_wrapped(&self, wrapper: &impl Fn(Python) -> PyObject) -> PyResult<()> {
let function = wrapper(self.py());
let name = function
.getattr(self.py(), "__name__")
.expect("A function or module must have a __name__");
self.add(name.extract(self.py()).unwrap(), function)
}
}