Skip to content

Commit fa346db

Browse files
committed
vm: use non-raising lookup for default attribute access
get_attribute_opt() backs hasattr() and getattr() with a default. It used get_attr_inner() for every object, then converted AttributeError from a missing attribute into None. The usual user-object miss therefore built and dropped an exception just to answer an optional lookup. Route objects using PyBaseObject::getattro through generic_getattr_opt(), which returns the missing case without constructing AttributeError. Objects with a custom getattro slot keep the raising path: their __getattribute__ and __getattr__ hooks can run Python code, so their exceptions must preserve the existing behavior. AttributeError from either route, including a descriptor, is still converted to None; non-AttributeError exceptions propagate. The new snippet covers ordinary hits and misses, custom __getattribute__ / __getattr__, descriptor exceptions, and dynamic getattro-slot updates. Refs youknowone#48 Assisted-by: Codex:GPT-5.6-terra
1 parent 30be390 commit fa346db

2 files changed

Lines changed: 137 additions & 4 deletions

File tree

‎crates/vm/src/vm/mod.rs‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ mod vm_ops;
2323
use crate::{
2424
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
2525
builtins::{
26-
self, PyBaseExceptionRef, PyDict, PyDictRef, PyInt, PyList, PyModule, PyStr, PyStrInterned,
27-
PyStrRef, PyTypeRef, PyUtf8Str, PyUtf8StrInterned, PyWeak,
26+
self, PyBaseExceptionRef, PyBaseObject, PyDict, PyDictRef, PyInt, PyList, PyModule, PyStr,
27+
PyStrInterned, PyStrRef, PyTypeRef, PyUtf8Str, PyUtf8StrInterned, PyWeak,
2828
code::PyCode,
2929
dict::{PyDictItems, PyDictKeys, PyDictValues},
3030
pystr::AsPyStr,
@@ -42,6 +42,7 @@ use crate::{
4242
scope::Scope,
4343
signal::{self, SignalHandlers},
4444
stdlib,
45+
types::{GetattroFunc, fn_addr},
4546
warn::WarningsState,
4647
};
4748
use alloc::{borrow::Cow, collections::BTreeMap};
@@ -2854,8 +2855,14 @@ impl VirtualMachine {
28542855
attr_name: impl AsPyStr<'a>,
28552856
) -> PyResult<Option<PyObjectRef>> {
28562857
let attr_name = attr_name.as_pystr(&self.ctx);
2857-
match obj.get_attr_inner(attr_name, self) {
2858-
Ok(attr) => Ok(Some(attr)),
2858+
let getattro = obj.class().slots.getattro.load().unwrap();
2859+
let result = if fn_addr(getattro) == fn_addr(PyBaseObject::getattro as GetattroFunc) {
2860+
obj.generic_getattr_opt(attr_name, None, self)
2861+
} else {
2862+
obj.get_attr_inner(attr_name, self).map(Some)
2863+
};
2864+
match result {
2865+
Ok(attr) => Ok(attr),
28592866
Err(e) if e.fast_isinstance(self.ctx.exceptions.attribute_error) => Ok(None),
28602867
Err(e) => Err(e),
28612868
}
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
def assert_raises(exc_type, func, *args):
2+
try:
3+
func(*args)
4+
except exc_type:
5+
return
6+
except BaseException as exc:
7+
raise AssertionError(
8+
f"expected {exc_type.__name__}, got {type(exc).__name__}"
9+
) from exc
10+
raise AssertionError(f"expected {exc_type.__name__}")
11+
12+
13+
class Plain:
14+
class_attr = "class"
15+
16+
17+
plain = Plain()
18+
plain.instance_attr = "instance"
19+
sentinel = object()
20+
21+
assert hasattr(plain, "class_attr")
22+
assert hasattr(plain, "instance_attr")
23+
assert not hasattr(plain, "missing")
24+
assert getattr(plain, "class_attr", sentinel) == "class"
25+
assert getattr(plain, "instance_attr", sentinel) == "instance"
26+
assert getattr(plain, "missing", sentinel) is sentinel
27+
assert_raises(AttributeError, getattr, plain, "missing")
28+
assert_raises(TypeError, hasattr, plain, 1)
29+
assert_raises(TypeError, getattr, plain, 1, sentinel)
30+
31+
32+
getattribute_calls = []
33+
34+
35+
class CustomGetattribute:
36+
def __getattribute__(self, name):
37+
getattribute_calls.append(name)
38+
if name == "missing":
39+
raise AttributeError("custom miss")
40+
if name == "bad":
41+
raise ValueError("custom error")
42+
return f"value:{name}"
43+
44+
45+
custom_getattribute = CustomGetattribute()
46+
assert not hasattr(custom_getattribute, "missing")
47+
assert getattr(custom_getattribute, "missing", sentinel) is sentinel
48+
assert getattribute_calls == ["missing", "missing"]
49+
assert getattr(custom_getattribute, "present", sentinel) == "value:present"
50+
assert_raises(ValueError, hasattr, custom_getattribute, "bad")
51+
52+
53+
getattr_calls = []
54+
55+
56+
class CustomGetattr:
57+
def __getattr__(self, name):
58+
getattr_calls.append(name)
59+
if name == "present":
60+
return "fallback value"
61+
if name == "bad":
62+
raise SystemExit("custom error")
63+
raise AttributeError(name)
64+
65+
66+
custom_getattr = CustomGetattr()
67+
assert getattr(custom_getattr, "present", sentinel) == "fallback value"
68+
assert not hasattr(custom_getattr, "missing")
69+
assert getattr_calls == ["present", "missing"]
70+
assert_raises(SystemExit, hasattr, custom_getattr, "bad")
71+
72+
73+
class AttributeErrorSubclass(AttributeError):
74+
pass
75+
76+
77+
class AttributeErrorDescriptor:
78+
def __get__(self, obj, owner):
79+
raise AttributeError("descriptor miss")
80+
81+
82+
class AttributeErrorSubclassDescriptor:
83+
def __get__(self, obj, owner):
84+
raise AttributeErrorSubclass("descriptor miss")
85+
86+
87+
class ValueErrorDescriptor:
88+
def __get__(self, obj, owner):
89+
raise ValueError("descriptor error")
90+
91+
92+
class DescriptorContainer:
93+
attribute_error = AttributeErrorDescriptor()
94+
attribute_error_subclass = AttributeErrorSubclassDescriptor()
95+
value_error = ValueErrorDescriptor()
96+
97+
98+
descriptor_container = DescriptorContainer()
99+
assert not hasattr(descriptor_container, "attribute_error")
100+
assert getattr(descriptor_container, "attribute_error", sentinel) is sentinel
101+
assert not hasattr(descriptor_container, "attribute_error_subclass")
102+
assert getattr(descriptor_container, "attribute_error_subclass", sentinel) is sentinel
103+
assert_raises(ValueError, hasattr, descriptor_container, "value_error")
104+
105+
106+
class Dynamic:
107+
pass
108+
109+
110+
dynamic = Dynamic()
111+
assert not hasattr(dynamic, "missing")
112+
dynamic_calls = []
113+
114+
115+
def dynamic_getattribute(self, name):
116+
dynamic_calls.append(name)
117+
if name == "missing":
118+
raise AttributeError(name)
119+
return object.__getattribute__(self, name)
120+
121+
122+
Dynamic.__getattribute__ = dynamic_getattribute
123+
assert not hasattr(dynamic, "missing")
124+
assert dynamic_calls == ["missing"]
125+
del Dynamic.__getattribute__
126+
assert not hasattr(dynamic, "missing")

0 commit comments

Comments
 (0)