Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
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
  • Loading branch information
key262yek committed Feb 14, 2025
commit dc0a75e903791aef9f8609b68bc74dc3e84fe71d
12 changes: 2 additions & 10 deletions vm/src/builtins/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
18 changes: 7 additions & 11 deletions vm/src/object/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use crate::{
lock::{PyMutex, PyMutexGuard, PyRwLock},
refcount::RefCount,
},
function::PySetterValue,
vm::VirtualMachine,
};
use itertools::Itertools;
Expand Down Expand Up @@ -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(()),
}
}

Expand Down