Skip to content

Commit 1266320

Browse files
committed
Provide more details in case of an import error
1 parent 416da17 commit 1266320

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/lib.rs

+12-8
Original file line numberDiff line numberDiff line change
@@ -106,26 +106,30 @@ impl From<&ImportError> for Error {
106106
}
107107

108108
/// Import and return a handle to the module `$m`.
109-
macro_rules! pyimport { ($m: literal) => {
109+
macro_rules! pyimport { ($name: path, $m: literal) => {
110110
Python::with_gil(|py|
111111
match PyModule::import_bound(py, intern!(py, $m)) {
112112
Ok(m) => Ok(m.into()),
113113
Err(e) => {
114-
let v = e.value_bound(py).to_string();
115-
Err(ImportError(v))
114+
let mut msg = stringify!($name).to_string();
115+
msg.push_str(": ");
116+
if let Ok(s) = e.value_bound(py).str() {
117+
let s = s.to_str().unwrap_or("Import error");
118+
msg.push_str(s)
119+
}
120+
Err(ImportError(msg))
116121
}
117122
})
118123
}}
119124

120-
// ⚠ Accessing these may try to lock Python's GIL. Make sure it is
121-
// executed outside a call to `Python::with_gil`.
122125
lazy_static! {
123-
// Import matplotlib modules.
126+
/// ⚠ Accessing these may try to lock Python's GIL. Make sure it is
127+
/// executed outside a call to `Python::with_gil`.
124128
static ref FIGURE: Result<Py<PyModule>, ImportError> = {
125-
pyimport!("matplotlib.figure")
129+
pyimport!(matplotlib::FIGURE, "matplotlib.figure")
126130
};
127131
static ref PYPLOT: Result<Py<PyModule>, ImportError> = {
128-
pyimport!("matplotlib.pyplot")
132+
pyimport!(matplotlib::PYPLOT, "matplotlib.pyplot")
129133
};
130134
}
131135

0 commit comments

Comments
 (0)