Skip to content

Commit fb553a6

Browse files
authored
Propagate module initialization and attribute control errors (#9712)
Assisted-by: OpenAI Codex:model version not exposed
1 parent 3fcaa16 commit fb553a6

9 files changed

Lines changed: 161 additions & 149 deletions

File tree

‎crates/derive-impl/src/pymodule.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,8 +399,8 @@ pub(crate) fn impl_pymodule(args: PyModuleArgs, module_item: Item) -> Result<Tok
399399
pub(crate) fn __init_dict(
400400
vm: &::rustpython_vm::VirtualMachine,
401401
module: &::rustpython_vm::Py<::rustpython_vm::builtins::PyModule>,
402-
) {
403-
::rustpython_vm::builtins::PyModule::__init_dict_from_def(vm, module);
402+
) -> ::rustpython_vm::PyResult<()> {
403+
::rustpython_vm::builtins::PyModule::__init_dict_from_def(vm, module)
404404
}
405405
},
406406
]);

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,15 @@ impl PyDict {
625625
}
626626
}
627627

628+
pub(crate) fn inner_pop_item<K: DictKey + ?Sized>(
629+
&self,
630+
key: &K,
631+
vm: &VirtualMachine,
632+
) -> PyResult<Option<PyObjectRef>> {
633+
let hash = Self::hash_or_unhashable(key, vm)?;
634+
self.entries.remove_if_exists(vm, key, hash)
635+
}
636+
628637
pub fn get_or_insert(
629638
&self,
630639
vm: &VirtualMachine,
@@ -1343,8 +1352,7 @@ impl Py<PyDict> {
13431352
vm: &VirtualMachine,
13441353
) -> PyResult<Option<PyObjectRef>> {
13451354
if self.exact_dict(vm) {
1346-
let hash = PyDict::hash_or_unhashable(key, vm)?;
1347-
self.entries.remove_if_exists(vm, key, hash)
1355+
self.inner_pop_item(key, vm)
13481356
} else {
13491357
let value = self.as_object().get_item(key, vm)?;
13501358
self.as_object().del_item(key, vm)?;

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

Lines changed: 77 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ use crate::{
55
class::PyClassImpl,
66
convert::ToPyObject,
77
function::{FuncArgs, PyMethodDef, PySetterValue},
8-
import::{get_spec_file_origin, is_possibly_shadowing_path, is_stdlib_module_name},
8+
import::{
9+
get_spec_file_origin, is_possibly_shadowing_path, is_spec_initializing,
10+
is_stdlib_module_name,
11+
},
912
types::{GetAttr, Initializer, Representable},
1013
};
1114
use rustpython_common::wtf8::wtf8_concat;
@@ -66,7 +69,7 @@ impl PyModuleDef {
6669
};
6770

6871
// Initialize module dict and methods
69-
PyModule::__init_dict_from_def(vm, &module);
72+
PyModule::__init_dict_from_def(vm, &module)?;
7073
module.__init_methods(vm)?;
7174

7275
Ok(module)
@@ -122,7 +125,7 @@ impl PyPayload for PyModule {
122125
pub struct ModuleInitArgs {
123126
name: PyStrRef,
124127
#[pyarg(any, default)]
125-
doc: Option<PyStrRef>,
128+
doc: Option<PyObjectRef>,
126129
}
127130

128131
impl PyModule {
@@ -159,9 +162,9 @@ impl PyModule {
159162
drop(self.native_state.store(Some(state)));
160163
}
161164

162-
pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py<Self>) {
163-
let doc = module.def.unwrap().doc.map(|doc| doc.to_owned());
164-
module.init_dict(module.name.unwrap(), doc, vm);
165+
pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py<Self>) -> PyResult<()> {
166+
let doc = module.def.unwrap().doc.map(|doc| doc.as_object());
167+
module.init_dict(module.name.unwrap(), doc, vm)
165168
}
166169
}
167170

@@ -185,7 +188,10 @@ impl Py<PyModule> {
185188
suppress_cycle: bool,
186189
vm: &VirtualMachine,
187190
) -> PyResult {
188-
let mut attr = self.as_object().generic_getattr_opt(name, None, vm)?;
191+
let mut attr = match self.as_object().generic_getattr_opt(name, None, vm) {
192+
Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.attribute_error) => None,
193+
result => result?,
194+
};
189195
if attr.is_none() {
190196
if let Some(value) =
191197
crate::lazy_import::try_load_submodule(self, name, suppress_cycle, vm)?
@@ -231,13 +237,13 @@ impl Py<PyModule> {
231237
{
232238
return getattr.call((name.to_owned(),), vm);
233239
}
240+
if suppress_cycle {
241+
return Err(vm.new_attribute_error(format!("module has no attribute '{name}'")));
242+
}
234243
let dict = self.dict();
235244

236245
// Get the raw __name__ object (may be a str subclass)
237-
let mod_name_obj = dict
238-
.get_item_opt(identifier!(vm, __name__), vm)
239-
.ok()
240-
.flatten();
246+
let mod_name_obj = dict.inner_getitem_opt(identifier!(vm, __name__), vm)?;
241247
let mod_name = mod_name_obj
242248
.as_ref()
243249
.and_then(|n| n.downcast_ref::<PyUtf8Str>());
@@ -247,13 +253,9 @@ impl Py<PyModule> {
247253
return Err(vm.new_attribute_error(format!("module has no attribute '{name}'")));
248254
};
249255

250-
let spec = dict
251-
.get_item_opt(vm.ctx.intern_str("__spec__"), vm)
252-
.ok()
253-
.flatten()
254-
.filter(|s| !vm.is_none(s));
256+
let spec = dict.inner_getitem_opt(vm.ctx.intern_str("__spec__"), vm)?;
255257

256-
let origin = get_spec_file_origin(spec.as_deref(), vm);
258+
let origin = get_spec_file_origin(spec.as_deref(), vm)?;
257259

258260
let is_possibly_shadowing = origin
259261
.as_ref()
@@ -279,7 +281,7 @@ impl Py<PyModule> {
279281
and prevents importing that standard library module)"
280282
)))
281283
} else {
282-
let is_initializing = PyModule::is_initializing(&dict, vm);
284+
let is_initializing = is_spec_initializing(spec.as_deref(), vm)?;
283285
if is_initializing {
284286
if is_possibly_shadowing {
285287
let origin = origin.as_ref().unwrap();
@@ -303,7 +305,7 @@ impl Py<PyModule> {
303305
}
304306
} else {
305307
// Check for uninitialized submodule
306-
let submodule_initializing = is_uninitialized_submodule(mod_name, name, vm);
308+
let submodule_initializing = is_uninitialized_submodule(spec.as_deref(), name, vm)?;
307309
if submodule_initializing {
308310
Err(vm.new_attribute_error(format!(
309311
"cannot access submodule '{name}' of module '{mod_display}' \
@@ -326,21 +328,16 @@ impl Py<PyModule> {
326328
// TODO: should be on PyModule, not Py<PyModule>
327329
pub(crate) fn init_dict(
328330
&self,
329-
name: &'static PyStrInterned,
330-
doc: Option<PyStrRef>,
331+
name: &Py<PyStr>,
332+
doc: Option<&PyObject>,
331333
vm: &VirtualMachine,
332-
) {
334+
) -> PyResult<()> {
333335
let dict = self.dict();
334-
dict.set_item(identifier!(vm, __name__), name.to_object(), vm)
335-
.expect("Failed to set __name__ on module");
336-
dict.set_item(identifier!(vm, __doc__), doc.to_pyobject(vm), vm)
337-
.expect("Failed to set __doc__ on module");
338-
dict.set_item("__package__", vm.ctx.none(), vm)
339-
.expect("Failed to set __package__ on module");
340-
dict.set_item("__loader__", vm.ctx.none(), vm)
341-
.expect("Failed to set __loader__ on module");
342-
dict.set_item("__spec__", vm.ctx.none(), vm)
343-
.expect("Failed to set __spec__ on module");
336+
dict.inner_setitem(identifier!(vm, __name__), name.to_owned().into(), vm)?;
337+
dict.inner_setitem(identifier!(vm, __doc__), doc.to_pyobject(vm), vm)?;
338+
dict.inner_setitem(vm.ctx.intern_str("__package__"), vm.ctx.none(), vm)?;
339+
dict.inner_setitem(vm.ctx.intern_str("__loader__"), vm.ctx.none(), vm)?;
340+
dict.inner_setitem(vm.ctx.intern_str("__spec__"), vm.ctx.none(), vm)
344341
}
345342

346343
pub fn get_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult {
@@ -363,38 +360,42 @@ impl Py<PyModule> {
363360
flags(BASETYPE, HAS_DICT, HAS_WEAKREF)
364361
)]
365362
impl PyModule {
363+
fn load_dict(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyDictRef> {
364+
zelf.as_object()
365+
.get_attr(identifier!(vm, __dict__), vm)?
366+
.downcast::<PyDict>()
367+
.map_err(|_| vm.new_type_error("<module>.__dict__ is not a dictionary"))
368+
}
369+
366370
#[pyslot]
367371
fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
368372
Self::new().into_ref_with_type(vm, cls).map(Into::into)
369373
}
370374

371375
#[pymethod]
372-
fn __dir__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
376+
fn __dir__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult {
373377
// First check if __dict__ attribute exists and is actually a dictionary
374-
let dict_attr = zelf.as_object().get_attr(identifier!(vm, __dict__), vm)?;
375-
let dict = dict_attr
376-
.downcast::<PyDict>()
377-
.map_err(|_| vm.new_type_error("<module>.__dict__ is not a dictionary"))?;
378+
let dict = Self::load_dict(zelf, vm)?;
378379
// PEP 562: honor a module-level __dir__ if one is defined
379380
if let Some(dir_func) =
380381
crate::lazy_import::resolved_dict_item(&dict, identifier!(vm, __dir__), vm)?
381382
{
382-
return dir_func.call((), vm)?.try_to_value(vm);
383+
return dir_func.call((), vm);
383384
}
384385
let attrs = dict.into_iter().map(|(k, _v)| k).collect();
385-
Ok(attrs)
386+
Ok(vm.ctx.new_list(attrs).into())
386387
}
387388

388389
#[pygetset]
389390
fn __annotate__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
390-
let dict = zelf.dict();
391+
let dict = Self::load_dict(zelf, vm)?;
391392
// Get __annotate__ from dict; if not present, insert None and return it
392393
// See: module_get_annotate()
393-
if let Some(annotate) = dict.get_item_opt(identifier!(vm, __annotate__), vm)? {
394+
if let Some(annotate) = dict.inner_getitem_opt(identifier!(vm, __annotate__), vm)? {
394395
Ok(annotate)
395396
} else {
396397
let none = vm.ctx.none();
397-
dict.set_item(identifier!(vm, __annotate__), none.clone(), vm)?;
398+
dict.inner_setitem(identifier!(vm, __annotate__), none.clone(), vm)?;
398399
Ok(none)
399400
}
400401
}
@@ -407,14 +408,14 @@ impl PyModule {
407408
) -> PyResult<()> {
408409
match value {
409410
PySetterValue::Assign(value) => {
411+
let dict = Self::load_dict(zelf, vm)?;
410412
if !vm.is_none(&value) && !value.is_callable() {
411413
return Err(vm.new_type_error("__annotate__ must be callable or None"));
412414
}
413-
let dict = zelf.dict();
414-
dict.set_item(identifier!(vm, __annotate__), value.clone(), vm)?;
415+
dict.inner_setitem(identifier!(vm, __annotate__), value.clone(), vm)?;
415416
// Clear __annotations__ if value is not None
416417
if !vm.is_none(&value) {
417-
dict.del_item(identifier!(vm, __annotations__), vm).ok();
418+
dict.inner_pop_item(identifier!(vm, __annotations__), vm)?;
418419
}
419420
Ok(())
420421
}
@@ -424,19 +425,23 @@ impl PyModule {
424425

425426
#[pygetset]
426427
fn __annotations__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
427-
let dict = zelf.dict();
428+
let dict = Self::load_dict(zelf, vm)?;
428429

429430
// Check if __annotations__ is already in dict (explicitly set)
430-
if let Some(annotations) = dict.get_item_opt(identifier!(vm, __annotations__), vm)? {
431+
if let Some(annotations) = dict.inner_getitem_opt(identifier!(vm, __annotations__), vm)? {
431432
return Ok(annotations);
432433
}
433434

434435
// Check if module is initializing
435-
let is_initializing = Self::is_initializing(&dict, vm);
436+
let spec = zelf
437+
.dict()
438+
.inner_getitem_opt(vm.ctx.intern_str("__spec__"), vm)?;
439+
let is_initializing = is_spec_initializing(spec.as_deref(), vm)?;
440+
drop(spec);
436441

437442
// PEP 649: Get __annotate__ and call it if callable
438443
let annotations = if let Some(annotate) =
439-
dict.get_item_opt(identifier!(vm, __annotate__), vm)?
444+
dict.inner_getitem_opt(identifier!(vm, __annotate__), vm)?
440445
&& annotate.is_callable()
441446
{
442447
// Call __annotate__(1) where 1 is FORMAT_VALUE
@@ -459,45 +464,34 @@ impl PyModule {
459464

460465
// Cache result unless module is initializing
461466
if !is_initializing {
462-
dict.set_item(identifier!(vm, __annotations__), annotations.clone(), vm)?;
467+
dict.inner_setitem(identifier!(vm, __annotations__), annotations.clone(), vm)?;
463468
}
464469

465470
Ok(annotations)
466471
}
467472

468-
/// Check if module is initializing via __spec__._initializing
469-
fn is_initializing(dict: &Py<PyDict>, vm: &VirtualMachine) -> bool {
470-
if let Ok(Some(spec)) = dict.get_item_opt(vm.ctx.intern_str("__spec__"), vm)
471-
&& let Ok(initializing) = spec.get_attr(vm.ctx.intern_str("_initializing"), vm)
472-
{
473-
return initializing.try_to_bool(vm).unwrap_or(false);
474-
}
475-
false
476-
}
477-
478473
#[pygetset(setter)]
479474
fn set___annotations__(
480475
zelf: &Py<Self>,
481476
value: PySetterValue,
482477
vm: &VirtualMachine,
483478
) -> PyResult<()> {
484-
let dict = zelf.dict();
485-
match value {
479+
let dict = Self::load_dict(zelf, vm)?;
480+
match &value {
486481
PySetterValue::Assign(value) => {
487-
dict.set_item(identifier!(vm, __annotations__), value, vm)?;
488-
// Clear __annotate__ from dict
489-
dict.del_item(identifier!(vm, __annotate__), vm).ok();
490-
Ok(())
482+
dict.inner_setitem(identifier!(vm, __annotations__), value.clone(), vm)?;
491483
}
492484
PySetterValue::Delete => {
493-
if dict.del_item(identifier!(vm, __annotations__), vm).is_err() {
485+
if dict
486+
.inner_pop_item(identifier!(vm, __annotations__), vm)?
487+
.is_none()
488+
{
494489
return Err(vm.new_attribute_error("__annotations__"));
495490
}
496-
// Also clear __annotate__
497-
dict.del_item(identifier!(vm, __annotate__), vm).ok();
498-
Ok(())
499491
}
500492
}
493+
dict.inner_pop_item(identifier!(vm, __annotate__), vm)?;
494+
Ok(())
501495
}
502496
}
503497

@@ -511,8 +505,8 @@ impl Initializer for PyModule {
511505
.flags
512506
.has_feature(crate::types::PyTypeFlags::HAS_DICT)
513507
);
514-
zelf.init_dict(vm.ctx.intern_str(args.name.as_wtf8()), args.doc, vm);
515-
Ok(())
508+
let ModuleInitArgs { name, doc } = args;
509+
zelf.init_dict(&name, doc.as_deref(), vm)
516510
}
517511
}
518512

@@ -542,31 +536,19 @@ pub(crate) fn init(context: &'static Context) {
542536
PyModule::extend_class(context, context.types.module_type);
543537
}
544538

545-
/// Check if {module_name}.{name} is an uninitialized submodule in sys.modules.
539+
/// Check the parent module's spec for an uninitialized submodule.
546540
fn is_uninitialized_submodule(
547-
module_name: Option<&Py<PyUtf8Str>>,
541+
spec: Option<&PyObject>,
548542
name: &Py<PyStr>,
549543
vm: &VirtualMachine,
550-
) -> bool {
551-
let Some(mod_name) = module_name else {
552-
return false;
553-
};
554-
555-
let Ok(sys_modules) = vm.sys_module.get_attr("modules", vm) else {
556-
return false;
544+
) -> PyResult<bool> {
545+
let Some(spec) = spec else {
546+
return Ok(false);
557547
};
558-
559-
let full_name = vm.ctx.new_utf8_str(format!("{}.{name}", mod_name.as_str()));
560-
let Ok(sub_mod) = sys_modules.get_item(&*full_name, vm) else {
561-
return false;
562-
};
563-
564-
let spec = match sub_mod.get_attr("__spec__", vm) {
565-
Ok(s) if !vm.is_none(&s) => s,
566-
_ => return false,
567-
};
568-
569-
spec.get_attr("_initializing", vm)
570-
.and_then(|v| v.try_to_bool(vm))
571-
.unwrap_or(false)
548+
match vm.get_attribute_opt(spec, "_uninitialized_submodules")? {
549+
Some(submodules) => submodules
550+
.sequence_unchecked()
551+
.contains(name.as_object(), vm),
552+
None => Ok(false),
553+
}
572554
}

0 commit comments

Comments
 (0)