Skip to content

Commit 17b11a0

Browse files
authored
Merge pull request RustPython#1578 from palaviv/with-traceback
with_traceback
2 parents 82c4c91 + 74b6d7c commit 17b11a0

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

tests/snippets/stdlib_traceback.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,25 @@
33
try:
44
1/0
55
except ZeroDivisionError as ex:
6-
tb = traceback.format_list(traceback.extract_tb(ex.__traceback__))
6+
tb = traceback.extract_tb(ex.__traceback__)
7+
assert len(tb) == 1
8+
9+
10+
try:
11+
try:
12+
1/0
13+
except ZeroDivisionError as ex:
14+
raise KeyError().with_traceback(ex.__traceback__)
15+
except KeyError as ex2:
16+
tb = traceback.extract_tb(ex2.__traceback__)
17+
assert tb[1].line == "1/0"
18+
19+
20+
try:
21+
try:
22+
1/0
23+
except ZeroDivisionError as ex:
24+
raise ex.with_traceback(None)
25+
except ZeroDivisionError as ex2:
26+
tb = traceback.extract_tb(ex2.__traceback__)
727
assert len(tb) == 1

vm/src/exceptions.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,19 @@ fn exception_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
208208
Ok(vm.new_str(joined_str))
209209
}
210210

211+
fn exception_with_traceback(
212+
zelf: PyObjectRef,
213+
tb: Option<PyTracebackRef>,
214+
vm: &VirtualMachine,
215+
) -> PyResult {
216+
vm.set_attr(
217+
&zelf,
218+
"__traceback__",
219+
tb.map_or(vm.get_none(), |tb| tb.into_object()),
220+
)?;
221+
Ok(zelf)
222+
}
223+
211224
#[derive(Debug)]
212225
pub struct ExceptionZoo {
213226
pub arithmetic_error: PyClassRef,
@@ -400,7 +413,8 @@ fn import_error_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
400413
pub fn init(context: &PyContext) {
401414
let base_exception_type = &context.exceptions.base_exception_type;
402415
extend_class!(context, base_exception_type, {
403-
"__init__" => context.new_rustfunc(exception_init)
416+
"__init__" => context.new_rustfunc(exception_init),
417+
"with_traceback" => context.new_rustfunc(exception_with_traceback)
404418
});
405419

406420
let exception_type = &context.exceptions.exception_type;

0 commit comments

Comments
 (0)