Creating interned pyclass instances #3076
Replies: 1 comment 3 replies
-
I think you need to avoid So maybe something like the following seems to work here: #[pyclass(frozen)]
struct Atom {
value: i32,
}
static CACHE: GILOnceCell<Mutex<HashMap<i32, Py<Atom>>>> = GILOnceCell::new();
#[pymethods]
impl Atom {
#[staticmethod]
fn of(py: Python<'_>, value: i32) -> Py<Atom> {
let cache = CACHE.get_or_init(py, || Mutex::new(HashMap::new())).lock().unwrap();
match cache.entry(value) {
Entry::Occupied(entry) => entry.into_mut().clone(),
Entry::Vacant(entry) => {
let atom = Py::new(py, Atom { value }).unwrap();
entry.insert(atom).clone()
}
}
}
} (The
I don't think so. We mostly rely on GitHub discussions and use a Gitter channel. So basically, I think you are at the right place.
You could put it into an attribute of your module using e.g. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I am trying to create a
pyclass
whose instances would be interned so that creating a new instance with the same internal value would return a pre-existing instance if there is one. I don't see how to do this at all with#[new]
. Any tips or other suggestions welcome!Also is there a mailing list for PyO3?
This Python code demonstrates what I want to achieve:
With that I can do:
I'm trying to achieve the same with a
pyclass
defined in pyo3 but stuck in a few ways. The code I have so far is:With that I get:
I've managed to intern objects at the rust level but the final output
False
shows that the two created Python objects are distinct. I think I understand why that is but I don't see how I could changePyAtom::py_new
to get it to do anything else. The function returns aPyAtom
struct which will then be converted by the caller into a Python object and if I understand correctly there is nothing I can return frompy_new
that would causeAtom(42)
to return a pre-existing Python object.Does anyone have any tips on how to achieve this?
I also realise that my static
CACHE
variable is not good but I'm not sure what is a better way. Naturally it would seem that I should make it be owned by something like say the type object but I don't see a way to attach it to the type object.Beta Was this translation helpful? Give feedback.
All reactions