diff --git a/src/once_cell.rs b/src/once_cell.rs index b759832f40c..9067e732ec2 100644 --- a/src/once_cell.rs +++ b/src/once_cell.rs @@ -141,12 +141,38 @@ impl GILOnceCell { /// ``` #[macro_export] macro_rules! intern { - ($py: expr, $text: literal) => {{ + ($py: expr, $text: expr) => {{ static INTERNED: $crate::once_cell::GILOnceCell<$crate::Py<$crate::types::PyString>> = $crate::once_cell::GILOnceCell::new(); INTERNED - .get_or_init($py, || $crate::types::PyString::intern($py, $text).into()) + .get_or_init($py, || { + $crate::conversion::IntoPy::into_py( + $crate::types::PyString::intern($py, $text), + $py, + ) + }) .as_ref($py) }}; } + +#[cfg(test)] +mod tests { + use super::*; + + use crate::types::PyDict; + + #[test] + fn test_intern() { + Python::with_gil(|py| { + let foo1 = "foo"; + let foo2 = intern!(py, "foo"); + let foo3 = intern!(py, stringify!(foo)); + + let dict = PyDict::new(py); + dict.set_item(foo1, 42_usize).unwrap(); + assert!(dict.contains(foo2).unwrap()); + assert_eq!(dict.get_item(foo3).unwrap().extract::().unwrap(), 42); + }); + } +} diff --git a/src/test_hygiene/misc.rs b/src/test_hygiene/misc.rs index eb49718e7ff..1c0baaa2a39 100644 --- a/src/test_hygiene/misc.rs +++ b/src/test_hygiene/misc.rs @@ -27,3 +27,9 @@ enum Derive4 { crate::create_exception!(mymodule, CustomError, crate::exceptions::PyException); crate::import_exception!(socket, gaierror); + +#[allow(dead_code)] +fn intern(py: crate::Python<'_>) { + let _foo = crate::intern!(py, "foo"); + let _bar = crate::intern!(py, stringify!(bar)); +}