Skip to content

Commit 9bdc2bb

Browse files
committed
Fix Exception.__str__
1 parent 076b975 commit 9bdc2bb

1 file changed

Lines changed: 18 additions & 9 deletions

File tree

vm/src/exceptions.rs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ pub fn print_exception_inner(vm: &VirtualMachine, exc: &PyObjectRef) {
119119
.unwrap()
120120
.downcast::<PyTuple>()
121121
.expect("'args' must be a tuple");
122-
let args_repr = exception_args_as_string(vm, varargs);
122+
let args_repr = exception_args_as_string(vm, varargs, true);
123123

124124
let exc_name = exc.class().name.clone();
125125
match args_repr.len() {
@@ -129,13 +129,22 @@ pub fn print_exception_inner(vm: &VirtualMachine, exc: &PyObjectRef) {
129129
}
130130
}
131131

132-
fn exception_args_as_string(vm: &VirtualMachine, varargs: PyTupleRef) -> Vec<String> {
132+
fn exception_args_as_string(
133+
vm: &VirtualMachine,
134+
varargs: PyTupleRef,
135+
str_single: bool,
136+
) -> Vec<String> {
133137
match varargs.elements.len() {
134138
0 => vec![],
135139
1 => {
136-
let args0_repr = vm
137-
.to_pystr(&varargs.elements[0])
138-
.unwrap_or_else(|_| "<element str() failed>".to_string());
140+
let args0_repr = if str_single {
141+
vm.to_pystr(&varargs.elements[0])
142+
.unwrap_or_else(|_| "<element str() failed>".to_string())
143+
} else {
144+
vm.to_repr(&varargs.elements[0])
145+
.map(|s| s.as_str().to_owned())
146+
.unwrap_or_else(|_| "<element repr() failed>".to_string())
147+
};
139148
vec![args0_repr]
140149
}
141150
_ => {
@@ -163,11 +172,11 @@ fn exception_str(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
163172
.unwrap()
164173
.downcast::<PyTuple>()
165174
.expect("'args' must be a tuple");
166-
let args_str = exception_args_as_string(vm, args);
175+
let args_str = exception_args_as_string(vm, args, false);
167176
let joined_str = match args_str.len() {
168177
0 => "".to_string(),
169-
1 => args_str[0].to_string(),
170-
_ => format!("({})", args_str.join(", ")),
178+
1 => args_str.into_iter().next().unwrap(),
179+
_ => format!("({})", args_str.into_iter().format(", ")),
171180
};
172181
Ok(vm.new_str(joined_str))
173182
}
@@ -183,7 +192,7 @@ fn exception_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
183192
.unwrap()
184193
.downcast::<PyTuple>()
185194
.expect("'args' must be a tuple");
186-
let args_repr = exception_args_as_string(vm, args);
195+
let args_repr = exception_args_as_string(vm, args, false);
187196

188197
let exc_name = exc.class().name.clone();
189198
let joined_str = match args_repr.len() {

0 commit comments

Comments
 (0)