Skip to content

Commit 80ec464

Browse files
committed
Use dict.update to combine class and object attrs in object_dir.
1 parent 664554b commit 80ec464

File tree

2 files changed

+23
-17
lines changed

2 files changed

+23
-17
lines changed

vm/src/obj/objdict.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,19 @@ impl PyDictRef {
239239
attrs
240240
}
241241

242+
pub fn from_attributes(attrs: PyAttributes, vm: &VirtualMachine) -> PyResult<Self> {
243+
let dict = DictContentType::default();
244+
let entries = RefCell::new(dict);
245+
246+
for (key, value) in attrs {
247+
entries
248+
.borrow_mut()
249+
.insert(vm, &vm.ctx.new_str(key), value)?;
250+
}
251+
252+
Ok(PyDict { entries }.into_ref(vm))
253+
}
254+
242255
fn hash(self, vm: &VirtualMachine) -> PyResult {
243256
Err(vm.new_type_error("unhashable type".to_string()))
244257
}

vm/src/obj/objobject.rs

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use super::objdict::PyDictRef;
22
use super::objlist::PyList;
3-
use super::objstr::{PyString, PyStringRef};
3+
use super::objstr::PyStringRef;
44
use super::objtype;
55
use crate::function::PyFuncArgs;
66
use crate::obj::objproperty::PropertyBuilder;
@@ -118,26 +118,19 @@ fn object_repr(zelf: PyObjectRef, _vm: &VirtualMachine) -> String {
118118
}
119119

120120
pub fn object_dir(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyList> {
121-
let mut attributes: PyAttributes = objtype::get_attributes(obj.class());
121+
let attributes: PyAttributes = objtype::get_attributes(obj.class());
122+
123+
let dict = PyDictRef::from_attributes(attributes, vm)?;
122124

123125
// Get instance attributes:
124-
if let Some(dict) = &obj.dict {
125-
for (key, value) in dict {
126-
if let Some(key_string) = key.payload::<PyString>() {
127-
attributes.insert(key_string.to_string(), value.clone());
128-
} else {
129-
return Err(vm.new_type_error(format!(
130-
"Attribute is not a string: {:?}",
131-
vm.to_pystr(&key)?
132-
)));
133-
}
134-
}
126+
if let Some(object_dict) = &obj.dict {
127+
vm.invoke(
128+
vm.get_attribute(dict.clone().into_object(), "update")?,
129+
object_dict.clone().into_object(),
130+
)?;
135131
}
136132

137-
let attributes: Vec<PyObjectRef> = attributes
138-
.keys()
139-
.map(|k| vm.ctx.new_str(k.to_string()))
140-
.collect();
133+
let attributes: Vec<_> = dict.into_iter().map(|(k, _v)| k.clone()).collect();
141134

142135
Ok(PyList::from(attributes))
143136
}

0 commit comments

Comments
 (0)