Skip to content

Commit 9033218

Browse files
committed
Be more defensive for running in interactive env.
1 parent 60bcd4c commit 9033218

File tree

4 files changed

+116
-59
lines changed

4 files changed

+116
-59
lines changed

crates/processing_pyo3/src/graphics.rs

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -581,20 +581,34 @@ fn parse_color(args: &[f32]) -> PyResult<(f32, f32, f32, f32)> {
581581
}
582582
}
583583

584-
pub fn get_graphics<'py>(module: &Bound<'py, PyModule>) -> PyResult<PyRef<'py, Graphics>> {
585-
module
586-
.getattr("_graphics")?
584+
pub fn get_graphics<'py>(module: &Bound<'py, PyModule>) -> PyResult<Option<PyRef<'py, Graphics>>> {
585+
let Ok(attr) = module.getattr("_graphics") else {
586+
return Ok(None);
587+
};
588+
if attr.is_none() {
589+
return Ok(None);
590+
}
591+
let g = attr
587592
.cast_into::<Graphics>()
588-
.map_err(|_| PyRuntimeError::new_err("no graphics context"))?
593+
.map_err(|_| PyRuntimeError::new_err("invalid graphics context"))?
589594
.try_borrow()
590-
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
595+
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
596+
Ok(Some(g))
591597
}
592598

593-
pub fn get_graphics_mut<'py>(module: &Bound<'py, PyModule>) -> PyResult<PyRefMut<'py, Graphics>> {
594-
module
595-
.getattr("_graphics")?
599+
pub fn get_graphics_mut<'py>(
600+
module: &Bound<'py, PyModule>,
601+
) -> PyResult<Option<PyRefMut<'py, Graphics>>> {
602+
let Ok(attr) = module.getattr("_graphics") else {
603+
return Ok(None);
604+
};
605+
if attr.is_none() {
606+
return Ok(None);
607+
}
608+
let g = attr
596609
.cast_into::<Graphics>()
597-
.map_err(|_| PyRuntimeError::new_err("no graphics context"))?
610+
.map_err(|_| PyRuntimeError::new_err("invalid graphics context"))?
598611
.try_borrow_mut()
599-
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
612+
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
613+
Ok(Some(g))
600614
}

0 commit comments

Comments
 (0)