Skip to content

Commit f90a5cf

Browse files
alok-108youknowone
andauthored
Fix del obj.__dict__ to match CPython behavior (fixes #5355) (#7568)
* Fix del obj.__dict__ to match CPython behavior (issue #5355) * Address CodeRabbit concerns: fix GC clearing and improve thread safety of lazy __dict__ recreation * Fix del obj.__dict__: improve GC safety, implement lazy re-creation in setattr, and enable passing CPython tests * Restore expectedFailure for test_has_inline_values * Fix ObjExt::new call site to include has_dict parameter * Remove stray test.py to avoid CI syntax errors * Remove debug txt files and clean test_class.py comments * Delete Lib/test/test_class.py * Restore test_class.py with correct changes (remove expectedFailure, no deletion) * Fix clippy warnings: remove unused into_inner, collapse nested if-let * Fix rustfmt formatting and ruff PEP 8 E302 blank line * Align __dict__ error messages and ensure safety for function/partial objects * Fix compilation errors: change &self to &Py<Self> in __dict__ methods * Fix compilation errors: resolve borrow-after-move and replace transpose on PySetterValue - type.rs: Replace invalid .transpose() on PySetterValue with explicit match on Assign/Delete variants in subtype_set_dict - function.rs: Fix borrow-after-move in set___dict__ by capturing class name before downcast; use as_object() for instance_dict/set_dict calls - _functools.rs: Same borrow-after-move fix and as_object() calls for PyPartial's __dict__ getter/setter * Fix compilation errors: resolve borrow-after-move and replace transpose on PySetterValue * Fix snippet formatting and mark test_remote as expected failure * Fix test_remote by removing HAS_DICT flag from function type * Fix lint formatting error * Remove unnecessary print statement in test_del_dict * Fix trailing newlines in snippet test * Trigger CI * Align __dict__ generic setter behavior * Move __dict__ deletion tests to relevant snippets --------- Co-authored-by: Jeong, YunWon <[email protected]>
1 parent 6c2c842 commit f90a5cf

11 files changed

Lines changed: 153 additions & 38 deletions

File tree

‎Lib/test/test_class.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -978,7 +978,6 @@ def __init__(self):
978978
obj.foo = None # Aborted here
979979
self.assertEqual(obj.__dict__, {"foo":None})
980980

981-
@unittest.expectedFailure # TODO: RUSTPYTHON
982981
def test_store_attr_deleted_dict(self):
983982
class Foo:
984983
pass
@@ -988,7 +987,6 @@ class Foo:
988987
f.a = 3
989988
self.assertEqual(f.a, 3)
990989

991-
@unittest.expectedFailure # TODO: RUSTPYTHON
992990
def test_rematerialize_object_dict(self):
993991
# gh-121860: rematerializing an object's managed dictionary after it
994992
# had been deleted caused a crash.

‎crates/vm/src/builtins/builtin_func.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ impl Representable for PyNativeFunction {
128128

129129
#[pyclass(
130130
with(Callable, Comparable, Representable),
131-
flags(HAS_DICT, HAS_WEAKREF, DISALLOW_INSTANTIATION)
131+
flags(HAS_WEAKREF, DISALLOW_INSTANTIATION)
132132
)]
133133
impl PyNativeFunction {
134134
#[pygetset]
@@ -209,7 +209,8 @@ pub struct PyNativeMethod {
209209

210210
// All Python-visible behavior (getters, slots) is registered by PyNativeFunction::extend_class.
211211
// PyNativeMethod only extends the Rust-side struct with the defining class reference.
212-
#[pyclass(flags(HAS_DICT, HAS_WEAKREF, DISALLOW_INSTANTIATION))]
212+
// The func field at offset 0 (#[repr(C)]) allows NativeFunctionOrMethod to read it safely.
213+
#[pyclass(flags(HAS_WEAKREF, DISALLOW_INSTANTIATION))]
213214
impl PyNativeMethod {}
214215

215216
impl fmt::Debug for PyNativeMethod {

‎crates/vm/src/builtins/function.rs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ mod jit;
33

44
use super::{
55
PyAsyncGen, PyCode, PyCoroutine, PyDictRef, PyGenerator, PyModule, PyStr, PyStrRef, PyTuple,
6-
PyTupleRef, PyType,
6+
PyTupleRef, PyType, object,
77
};
88
use crate::common::hash::PyHash;
99
use crate::common::lock::PyMutex;
@@ -954,6 +954,16 @@ impl PyFunction {
954954
Ok(())
955955
}
956956

957+
#[pygetset]
958+
fn __dict__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyDictRef> {
959+
object::object_get_dict(zelf.as_object().to_owned(), vm)
960+
}
961+
962+
#[pygetset(setter)]
963+
fn set___dict__(zelf: &Py<Self>, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
964+
object::object_generic_set_dict(zelf.as_object().to_owned(), value, vm)
965+
}
966+
957967
#[pygetset]
958968
fn __annotate__(&self, vm: &VirtualMachine) -> PyObjectRef {
959969
self.annotate

‎crates/vm/src/builtins/object.rs‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{PyDictRef, PyList, PyStr, PyStrRef, PyType, PyTypeRef, PyUtf8StrRef};
1+
use super::{PyDict, PyDictRef, PyList, PyStr, PyStrRef, PyType, PyTypeRef, PyUtf8StrRef};
22
use crate::common::hash::PyHash;
33
use crate::types::PyTypeFlags;
44
use crate::{
@@ -554,14 +554,48 @@ impl PyBaseObject {
554554
}
555555

556556
pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyDictRef> {
557-
obj.dict()
558-
.ok_or_else(|| vm.new_attribute_error("This object has no __dict__"))
557+
if let Some(dict) = obj.dict() {
558+
Ok(dict)
559+
} else {
560+
match obj.instance_dict() {
561+
Some(d) => Ok(d.get_or_insert(vm)),
562+
None => Err(vm.new_attribute_error("This object has no __dict__")),
563+
}
564+
}
559565
}
560-
pub fn object_set_dict(obj: PyObjectRef, dict: PyDictRef, vm: &VirtualMachine) -> PyResult<()> {
566+
pub fn object_set_dict(
567+
obj: PyObjectRef,
568+
value: PySetterValue<PyDictRef>,
569+
vm: &VirtualMachine,
570+
) -> PyResult<()> {
571+
let dict = match value {
572+
PySetterValue::Assign(dict) => Some(dict),
573+
PySetterValue::Delete => None,
574+
};
561575
obj.set_dict(dict)
562576
.map_err(|_| vm.new_attribute_error("This object has no __dict__"))
563577
}
564578

579+
pub fn object_generic_set_dict(
580+
obj: PyObjectRef,
581+
value: PySetterValue,
582+
vm: &VirtualMachine,
583+
) -> PyResult<()> {
584+
let dict = match value {
585+
PySetterValue::Assign(value) => {
586+
let dict = value.downcast::<PyDict>().map_err(|value| {
587+
vm.new_type_error(format!(
588+
"__dict__ must be set to a dictionary, not a '{}'",
589+
value.class().name()
590+
))
591+
})?;
592+
PySetterValue::Assign(dict)
593+
}
594+
PySetterValue::Delete => return Err(vm.new_type_error("cannot delete __dict__")),
595+
};
596+
object_set_dict(obj, dict, vm)
597+
}
598+
565599
pub fn init(ctx: &'static Context) {
566600
// Manually set alloc/init slots - derive macro doesn't generate extend_slots
567601
// for trait impl that overrides #[pyslot] method

‎crates/vm/src/builtins/type.rs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2643,7 +2643,7 @@ fn subtype_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
26432643
}
26442644

26452645
// = subtype_setdict
2646-
fn subtype_set_dict(obj: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
2646+
fn subtype_set_dict(obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
26472647
let base = get_builtin_base_with_dict(obj.class(), vm);
26482648

26492649
if let Some(base_type) = base {
@@ -2655,13 +2655,17 @@ fn subtype_set_dict(obj: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -
26552655
.descr_set
26562656
.load()
26572657
.ok_or_else(|| raise_dict_descriptor_error(&obj, vm))?;
2658-
descr_set(&descr, obj, PySetterValue::Assign(value), vm)
2658+
descr_set(&descr, obj, value, vm)
26592659
} else {
26602660
Err(raise_dict_descriptor_error(&obj, vm))
26612661
}
26622662
} else {
2663-
// PyObject_GenericSetDict
2664-
object::object_set_dict(obj, value.try_into_value(vm)?, vm)?;
2663+
// _PyObject_SetDict
2664+
let value = match value {
2665+
PySetterValue::Assign(obj) => PySetterValue::Assign(obj.try_into_value(vm)?),
2666+
PySetterValue::Delete => PySetterValue::Delete,
2667+
};
2668+
object::object_set_dict(obj, value, vm)?;
26652669
Ok(())
26662670
}
26672671
}

‎crates/vm/src/object/core.rs‎

Lines changed: 40 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -307,9 +307,13 @@ pub(super) struct ObjExt {
307307
}
308308

309309
impl ObjExt {
310-
fn new(dict: Option<PyDictRef>, member_count: usize) -> Self {
310+
fn new(dict: Option<PyDictRef>, member_count: usize, has_dict: bool) -> Self {
311311
Self {
312-
dict: dict.map(InstanceDict::new),
312+
dict: if has_dict {
313+
Some(InstanceDict::from_opt(dict))
314+
} else {
315+
None
316+
},
313317
slots: core::iter::repeat_with(|| PyRwLock::new(None))
314318
.take(member_count)
315319
.collect_vec()
@@ -933,8 +937,8 @@ impl Py<PyWeak> {
933937
}
934938

935939
#[derive(Debug)]
936-
pub(super) struct InstanceDict {
937-
pub(super) d: PyRwLock<PyDictRef>,
940+
pub(crate) struct InstanceDict {
941+
pub(crate) d: PyRwLock<Option<PyDictRef>>,
938942
}
939943

940944
impl From<PyDictRef> for InstanceDict {
@@ -947,30 +951,45 @@ impl From<PyDictRef> for InstanceDict {
947951
impl InstanceDict {
948952
#[inline]
949953
pub const fn new(d: PyDictRef) -> Self {
954+
Self {
955+
d: PyRwLock::new(Some(d)),
956+
}
957+
}
958+
959+
#[inline]
960+
pub const fn from_opt(d: Option<PyDictRef>) -> Self {
950961
Self {
951962
d: PyRwLock::new(d),
952963
}
953964
}
954965

955966
#[inline]
956-
pub fn get(&self) -> PyDictRef {
967+
pub fn get(&self) -> Option<PyDictRef> {
957968
self.d.read().clone()
958969
}
959970

960971
#[inline]
961-
pub fn set(&self, d: PyDictRef) {
972+
pub fn set(&self, d: Option<PyDictRef>) {
962973
self.replace(d);
963974
}
964975

965976
#[inline]
966-
pub fn replace(&self, d: PyDictRef) -> PyDictRef {
977+
pub fn replace(&self, d: Option<PyDictRef>) -> Option<PyDictRef> {
967978
core::mem::replace(&mut self.d.write(), d)
968979
}
969980

970-
/// Consume the InstanceDict and return the inner PyDictRef.
971-
#[inline]
972-
pub fn into_inner(self) -> PyDictRef {
973-
self.d.into_inner()
981+
pub(crate) fn get_or_insert(&self, vm: &VirtualMachine) -> PyDictRef {
982+
if let Some(existing) = self.d.read().as_ref() {
983+
return existing.clone();
984+
}
985+
let dict = vm.ctx.new_dict();
986+
let mut d = self.d.write();
987+
if let Some(existing) = d.as_ref() {
988+
existing.clone()
989+
} else {
990+
*d = Some(dict.clone());
991+
dict
992+
}
974993
}
975994
}
976995

@@ -1084,7 +1103,11 @@ impl<T: PyPayload + core::fmt::Debug> PyInner<T> {
10841103
unsafe {
10851104
if let Some(offset) = ext_start {
10861105
let ext_ptr = alloc_ptr.add(offset) as *mut ObjExt;
1087-
ext_ptr.write(ObjExt::new(dict, member_count));
1106+
let has_dict = typ
1107+
.slots
1108+
.flags
1109+
.has_feature(crate::types::PyTypeFlags::HAS_DICT);
1110+
ext_ptr.write(ObjExt::new(dict, member_count, has_dict));
10881111
}
10891112

10901113
if let Some(offset) = weakref_start {
@@ -1476,18 +1499,18 @@ impl PyObject {
14761499
}
14771500

14781501
#[inline(always)]
1479-
fn instance_dict(&self) -> Option<&InstanceDict> {
1502+
pub(crate) fn instance_dict(&self) -> Option<&InstanceDict> {
14801503
self.0.ext_ref().and_then(|ext| ext.dict.as_ref())
14811504
}
14821505

14831506
#[inline(always)]
14841507
pub fn dict(&self) -> Option<PyDictRef> {
1485-
self.instance_dict().map(|d| d.get())
1508+
self.instance_dict().and_then(|d| d.get())
14861509
}
14871510

14881511
/// Set the dict field. Returns `Err(dict)` if this object does not have a dict field
14891512
/// in the first place.
1490-
pub fn set_dict(&self, dict: PyDictRef) -> Result<(), PyDictRef> {
1513+
pub fn set_dict(&self, dict: Option<PyDictRef>) -> Result<(), Option<PyDictRef>> {
14911514
match self.instance_dict() {
14921515
Some(d) => {
14931516
d.set(dict);
@@ -1799,9 +1822,7 @@ impl PyObject {
17991822
let ext_ptr =
18001823
core::ptr::with_exposed_provenance_mut::<ObjExt>(self_addr.wrapping_sub(offset));
18011824
let ext = unsafe { &mut *ext_ptr };
1802-
if let Some(old_dict) = ext.dict.take() {
1803-
// Get the dict ref before dropping InstanceDict
1804-
let dict_ref = old_dict.into_inner();
1825+
if let Some(dict_ref) = ext.dict.as_ref().and_then(|d| d.replace(None)) {
18051826
result.push(dict_ref.into());
18061827
}
18071828
for slot in ext.slots.iter() {
@@ -2471,7 +2492,7 @@ pub(crate) fn init_type_hierarchy() -> (PyTypeRef, PyTypeRef, PyTypeRef) {
24712492

24722493
unsafe {
24732494
let ext_ptr = alloc_ptr as *mut ObjExt;
2474-
ext_ptr.write(ObjExt::new(None, 0));
2495+
ext_ptr.write(ObjExt::new(None, 0, true));
24752496

24762497
let weakref_ptr = alloc_ptr.add(weakref_offset) as *mut WeakRefList;
24772498
weakref_ptr.write(WeakRefList::new());

‎crates/vm/src/protocol/object.rs‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -199,17 +199,21 @@ impl PyObject {
199199
}
200200
}
201201

202-
if let Some(dict) = self.dict() {
202+
if let Some(instance_dict) = self.instance_dict() {
203203
if let PySetterValue::Assign(value) = value {
204-
dict.set_item(attr_name, value, vm)?;
205-
} else {
204+
instance_dict
205+
.get_or_insert(vm)
206+
.set_item(attr_name, value, vm)?;
207+
} else if let Some(dict) = instance_dict.get() {
206208
dict.del_item(attr_name, vm).map_err(|e| {
207209
if e.fast_isinstance(vm.ctx.exceptions.key_error) {
208210
vm.new_no_attribute_error(self.to_owned(), attr_name.to_owned())
209211
} else {
210212
e
211213
}
212214
})?;
215+
} else {
216+
return Err(vm.new_no_attribute_error(self.to_owned(), attr_name.to_owned()));
213217
}
214218
Ok(())
215219
} else {

‎crates/vm/src/stdlib/_functools.rs‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ pub(crate) use _functools::module_def;
44
mod _functools {
55
use crate::{
66
Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
7-
builtins::{PyBoundMethod, PyDict, PyGenericAlias, PyTuple, PyType, PyTypeRef},
7+
builtins::{
8+
PyBoundMethod, PyDict, PyDictRef, PyGenericAlias, PyTuple, PyType, PyTypeRef, object,
9+
},
810
common::lock::PyRwLock,
9-
function::{FuncArgs, KwArgs, OptionalOption},
11+
function::{FuncArgs, KwArgs, OptionalOption, PySetterValue},
1012
object::AsObject,
1113
protocol::PyIter,
1214
pyclass,
@@ -158,6 +160,23 @@ mod _functools {
158160
self.inner.read().keywords.clone()
159161
}
160162

163+
#[pygetset]
164+
fn __dict__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyDictRef {
165+
zelf.as_object()
166+
.instance_dict()
167+
.map(|d| d.get_or_insert(vm))
168+
.unwrap_or_else(|| vm.ctx.new_dict())
169+
}
170+
171+
#[pygetset(setter)]
172+
fn set___dict__(
173+
zelf: &Py<Self>,
174+
value: PySetterValue,
175+
vm: &VirtualMachine,
176+
) -> PyResult<()> {
177+
object::object_generic_set_dict(zelf.as_object().to_owned(), value, vm)
178+
}
179+
161180
#[pymethod]
162181
fn __reduce__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult {
163182
let inner = zelf.inner.read();

‎extra_tests/snippets/builtin_object.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,17 @@ class MyObject:
2626
obj.__dict__ = {"a": 1}
2727
assert obj.a == 1
2828

29+
del obj.__dict__
30+
d = obj.__dict__
31+
assert isinstance(d, dict)
32+
assert len(d) == 0
33+
34+
try:
35+
obj.a
36+
assert False, "AttributeError expected"
37+
except AttributeError:
38+
pass
39+
2940
# Value inside the formatter goes through a different path of resolution.
3041
# Check that it still works all the same
3142
d = {

‎extra_tests/snippets/stdlib_functools.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from functools import reduce
1+
from functools import partial, reduce
22

33
from testutils import assert_raises
44

@@ -90,3 +90,10 @@ def __getitem__(self, i):
9090

9191
d = {"one": 1, "two": 2, "three": 3}
9292
assert reduce(add, d) == "".join(d.keys())
93+
94+
p = partial(add)
95+
try:
96+
del p.__dict__
97+
assert False, "TypeError expected for partial dict deletion"
98+
except TypeError:
99+
pass

0 commit comments

Comments
 (0)