Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
55 changes: 41 additions & 14 deletions crates/vm/src/protocol/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, TryFromObject, VirtualMachine,
builtins::{
PyBaseObject, PyBytes, PyDict, PyDictRef, PyGenericAlias, PyInt, PyListRef, PyStr, PyTuple,
PyTupleRef, PyType, PyTypeRef, PyUtf8Str, int::check_int_to_str_digits, pystr::AsPyStr,
PyBaseExceptionRef, PyBaseObject, PyBytes, PyDict, PyDictRef, PyGenericAlias, PyInt,
PyListRef, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef, PyUtf8Str,
int::check_int_to_str_digits, pystr::AsPyStr,
},
common::{hash::PyHash, str::to_ascii},
convert::ToPyObject,
dict_inner::DictKey,
function::{Either, FuncArgs, PyArithmeticValue, PySetterValue},
protocol::PyIter,
types::{Constructor, PyComparisonOp},
types::{Constructor, PyComparisonOp, PyTypeFlags},
};

/// Converts an index key the way a sequence does before it refuses the
Expand Down Expand Up @@ -231,19 +232,33 @@ impl PyObject {
return Err(exc);
};

// Only the object key runs a `str` subclass's `__hash__`.
let exact_str = attr_name.class().is(vm.ctx.types.str_type);
// A `KeyError` raised by that `__hash__` reads as a missing attribute
// too, on assignment as well as on deletion.
let key_error_to_attribute_error = |e: PyBaseExceptionRef| {
if e.fast_isinstance(vm.ctx.exceptions.key_error) {
vm.new_no_attribute_error(self.to_owned(), attr_name.to_owned())
} else {
e
}
};
if let PySetterValue::Assign(value) = value {
instance_dict
.get_or_insert(vm)
.set_item(attr_name, value, vm)?;
let dict = instance_dict.get_or_insert(vm);
if exact_str {
dict.set_item(attr_name, value, vm)
} else {
dict.set_item(attr_name.as_object(), value, vm)
}
.map_err(key_error_to_attribute_error)?;
instance_dict.maybe_materialize_inline_values();
} else if let Some(dict) = instance_dict.get() {
dict.del_item(attr_name, vm).map_err(|e| {
if e.fast_isinstance(vm.ctx.exceptions.key_error) {
vm.new_no_attribute_error(self.to_owned(), attr_name.to_owned())
} else {
e
}
})?;
if exact_str {
dict.del_item(attr_name, vm)
} else {
dict.del_item(attr_name.as_object(), vm)
}
.map_err(key_error_to_attribute_error)?;
} else {
return Err(vm.new_no_attribute_error(self.to_owned(), attr_name.to_owned()));
}
Expand Down Expand Up @@ -284,7 +299,19 @@ impl PyObject {
let attr = if let Some(dict) = dict {
// `Py<PyStr>` rather than its `&Wtf8`: the key type carries the
// cached hash and compares interned keys by pointer.
dict.get_item_opt(name_str, vm)?
if name_str.class().is(vm.ctx.types.str_type) {
dict.get_item_opt(name_str, vm)?
} else if dict.is_empty()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
&& !(obj_cls.slots.flags.has_feature(PyTypeFlags::MANAGED_DICT)
&& obj_cls.slots.itemsize == 0)
{
// An empty dict that is not a managed one stands for a dict
// not created yet: skip the lookup.
None
Comment thread
jseop-lim marked this conversation as resolved.
Resolved
} else {
// Only the object key runs a subclass's `__hash__`.
dict.get_item_opt(name_str.as_object(), vm)?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update thread-local writes to use the same subclass hash

For threading.local(), a str subclass whose stable hash differs from the underlying string’s hash now breaks setattr(local, Name("x"), 1); getattr(local, Name("x")): the lookup raises AttributeError instead of returning 1. Local::getattro delegates to this branch (crates/vm/src/stdlib/_thread.rs:1458), but Local::setattro still passes attr: &Py<PyStr> to dict.set_item/del_item (lines 1492–1495), so assignment stores the built-in string hash while lookup uses the subclass hash. This round trip worked before the change and succeeds in CPython 3.14. Update the thread-local assignment/deletion paths to use object keys for subclass names too.

Useful? React with 👍 / 👎.

}
} else {
None
};
Expand Down
46 changes: 46 additions & 0 deletions extra_tests/snippets/builtin_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,49 @@ def __getattribute__(self, name):
_GABase.__getattr__ = lambda self, name: "fallback"
del _GABase.__getattr__
assert _GAProxy().x == "hooked"


class RaisingHashName(str):
def __hash__(self):
raise ZeroDivisionError


with assert_raises(ZeroDivisionError):
getattr(MyObject(), RaisingHashName("x"), None)
with assert_raises(ZeroDivisionError):
hasattr(MyObject(), RaisingHashName("x"))
with assert_raises(ZeroDivisionError):
setattr(MyObject(), RaisingHashName("x"), 1)
assert getattr(object(), RaisingHashName("x"), None) is None


class OwnHashName(str):
def __hash__(self):
return 1


obj = MyObject()
setattr(obj, OwnHashName("x"), 1)
assert getattr(obj, OwnHashName("x")) == 1
delattr(obj, OwnHashName("x"))
assert obj.__dict__ == {}

obj = MyObject()
obj.x = 1
with assert_raises(ZeroDivisionError):
delattr(obj, RaisingHashName("x"))
assert obj.__dict__ == {"x": 1}


class KeyErrorHashName(str):
def __hash__(self):
raise KeyError


with assert_raises(AttributeError):
setattr(MyObject(), KeyErrorHashName("x"), 1)
obj = MyObject()
obj.x = 1
with assert_raises(AttributeError):
delattr(obj, KeyErrorHashName("x"))
assert obj.__dict__ == {"x": 1}
Loading