Refactor object dictionary setter to handle delete and assign operations

- Simplify object_set_dict method in object.rs
- Update set_dict method in core.rs to handle both assignment and deletion
- Consolidate dictionary modification logic
This commit is contained in:
2025-02-15 00:12:19 +09:00
parent c40d24ed68
commit dc0a75e903
2 changed files with 9 additions and 21 deletions

View File

@@ -497,16 +497,8 @@ pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyDict
}
pub fn object_set_dict(obj: PyObjectRef, dict: PySetterValue<PyDictRef>, vm: &VirtualMachine) -> PyResult<()> {
match dict {
PySetterValue::Assign(dict) => {
obj.set_dict(dict)
.map_err(|_| vm.new_attribute_error("This object has no __dict__".to_owned()))
}
PySetterValue::Delete => {
obj.delete_dict()
.map_err(|_| vm.new_attribute_error("This object has no deletable __dict__".to_owned()))
}
}
obj.set_dict(dict)
.map_err(|_| vm.new_attribute_error("This object has no __dict__".to_owned()))
}
pub fn init(ctx: &Context) {

View File

@@ -25,6 +25,7 @@ use crate::{
lock::{PyMutex, PyMutexGuard, PyRwLock},
refcount::RefCount,
},
function::PySetterValue,
vm::VirtualMachine,
};
use itertools::Itertools;
@@ -707,26 +708,21 @@ impl PyObject {
/// Set the dict field. Returns `Err(dict)` if this object does not have a dict field
/// in the first place.
pub fn set_dict(&self, dict: PyDictRef) -> Result<(), PyDictRef> {
match self.instance_dict() {
Some(d) => {
pub fn set_dict(&self, dict: PySetterValue<PyDictRef>) -> Result<(), PyDictRef> {
match (self.instance_dict(), dict) {
(Some(d), PySetterValue::Assign(dict)) => {
d.set(dict);
Ok(())
}
None => Err(dict),
}
}
pub fn delete_dict(&self) -> Result<(), ()> {
match self.instance_dict() {
Some(_) => {
(None, PySetterValue::Assign(dict)) => Err(dict),
(Some(_), PySetterValue::Delete) => {
unsafe {
let ptr = self as *const _ as *mut PyObject;
(*ptr).0.dict = None;
}
Ok(())
}
None => Err(()),
(None, PySetterValue::Delete) => Ok(()),
}
}