Skip to content

with_traceback #1578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion tests/snippets/stdlib_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,25 @@
try:
1/0
except ZeroDivisionError as ex:
tb = traceback.format_list(traceback.extract_tb(ex.__traceback__))
tb = traceback.extract_tb(ex.__traceback__)
assert len(tb) == 1


try:
try:
1/0
except ZeroDivisionError as ex:
raise KeyError().with_traceback(ex.__traceback__)
except KeyError as ex2:
tb = traceback.extract_tb(ex2.__traceback__)
assert tb[1].line == "1/0"


try:
try:
1/0
except ZeroDivisionError as ex:
raise ex.with_traceback(None)
except ZeroDivisionError as ex2:
tb = traceback.extract_tb(ex2.__traceback__)
assert len(tb) == 1
16 changes: 15 additions & 1 deletion vm/src/exceptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,19 @@ fn exception_repr(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
Ok(vm.new_str(joined_str))
}

fn exception_with_traceback(
zelf: PyObjectRef,
tb: Option<PyTracebackRef>,
vm: &VirtualMachine,
) -> PyResult {
vm.set_attr(
&zelf,
"__traceback__",
tb.map_or(vm.get_none(), |tb| tb.into_object()),
)?;
Ok(zelf)
}

#[derive(Debug)]
pub struct ExceptionZoo {
pub arithmetic_error: PyClassRef,
Expand Down Expand Up @@ -400,7 +413,8 @@ fn import_error_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
pub fn init(context: &PyContext) {
let base_exception_type = &context.exceptions.base_exception_type;
extend_class!(context, base_exception_type, {
"__init__" => context.new_rustfunc(exception_init)
"__init__" => context.new_rustfunc(exception_init),
"with_traceback" => context.new_rustfunc(exception_with_traceback)
});

let exception_type = &context.exceptions.exception_type;
Expand Down