Skip to content

Commit 5cc5899

Browse files
committed
Infer struct sequence module name from __module__ attribute in repr
slot_repr now checks the __module__ attribute set by #[pymodule] at runtime, so explicit module = "..." in #[pystruct_sequence] is no longer needed for types defined inside a #[pymodule].
1 parent add2539 commit 5cc5899

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

crates/vm/src/types/structseq.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::common::lock::LazyLock;
22
use crate::{
33
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func,
4-
builtins::{PyBaseExceptionRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef},
4+
builtins::{PyBaseExceptionRef, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef},
55
class::{PyClassImpl, StaticType},
66
function::{Either, FuncArgs, PyComparisonValue, PyMethodDef, PyMethodFlags},
77
iter::PyExactSizeIterator,
@@ -225,7 +225,21 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
225225
} else {
226226
(String::new(), "...")
227227
};
228-
let repr_str = format!("{}({}{})", Self::TP_NAME, body, suffix);
228+
// Build qualified name: if MODULE_NAME is already in TP_NAME, use it directly.
229+
// Otherwise, check __module__ attribute (set by #[pymodule] at runtime).
230+
let type_name = if Self::MODULE_NAME.is_some() {
231+
alloc::borrow::Cow::Borrowed(Self::TP_NAME)
232+
} else {
233+
let typ = zelf.class();
234+
match typ.get_attr(identifier!(vm.ctx, __module__)) {
235+
Some(module) if module.downcastable::<PyStr>() => {
236+
let module_str = module.downcast_ref::<PyStr>().unwrap();
237+
alloc::borrow::Cow::Owned(format!("{}.{}", module_str.as_str(), Self::NAME))
238+
}
239+
_ => alloc::borrow::Cow::Borrowed(Self::TP_NAME),
240+
}
241+
};
242+
let repr_str = format!("{}({}{})", type_name, body, suffix);
229243
Ok(vm.ctx.new_str(repr_str))
230244
}
231245

0 commit comments

Comments
 (0)