Skip to content

Commit 3e42edd

Browse files
committed
dict.__new__ - support for dict subtypes.
1 parent 42bb346 commit 3e42edd

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

tests/snippets/dict.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@ def dict_eq(d1, d2):
5757
assert x.get("here", "default") == "here"
5858
assert x.get("not here") == None
5959

60+
class LengthDict(dict):
61+
pass
62+
63+
x = LengthDict()
64+
assert type(x) == LengthDict
65+
66+
6067
# An object that hashes to the same value always, and compares equal if any its values match.
6168
class Hashable(object):
6269
def __init__(self, *args):

vm/src/obj/objdict.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,18 @@ impl PyValue for PyDict {
4040
// Python dict methods:
4141
impl PyDictRef {
4242
fn new(
43-
_class: PyClassRef, // TODO Support subclasses of int.
43+
class: PyClassRef,
4444
dict_obj: OptionalArg<PyObjectRef>,
4545
kwargs: KwArgs,
4646
vm: &VirtualMachine,
4747
) -> PyResult<PyDictRef> {
48-
let dict = vm.ctx.new_dict();
48+
let mut dict = DictContentType::default();
49+
4950
if let OptionalArg::Present(dict_obj) = dict_obj {
5051
let dicted: PyResult<PyDictRef> = dict_obj.clone().downcast();
5152
if let Ok(dict_obj) = dicted {
5253
for (key, value) in dict_obj.get_key_value_pairs() {
53-
dict.set_item(key, value, vm);
54+
dict.insert(vm, &key, value)?;
5455
}
5556
} else {
5657
let iter = objiter::get_iter(vm, &dict_obj)?;
@@ -68,14 +69,17 @@ impl PyDictRef {
6869
if objiter::get_next_object(vm, &elem_iter)?.is_some() {
6970
return Err(err(vm));
7071
}
71-
dict.set_item(key, value, vm);
72+
dict.insert(vm, &key, value)?;
7273
}
7374
}
7475
}
7576
for (key, value) in kwargs.into_iter() {
76-
dict.set_item(vm.new_str(key), value, vm);
77+
dict.insert(vm, &vm.new_str(key), value)?;
78+
}
79+
PyDict {
80+
entries: RefCell::new(dict),
7781
}
78-
Ok(dict)
82+
.into_ref_with_type(vm, class)
7983
}
8084

8185
fn bool(self, _vm: &VirtualMachine) -> bool {

0 commit comments

Comments
 (0)