Skip to content

Commit 9ce5240

Browse files
committed
add name, path, msg attributes to ImportError
1 parent df53d55 commit 9ce5240

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

tests/snippets/exceptions.py

+20
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# KeyError
12
empty_exc = KeyError()
23
assert str(empty_exc) == ''
34
assert repr(empty_exc) == 'KeyError()'
@@ -23,3 +24,22 @@ def __str__(self):
2324
exc = KeyError(A())
2425
assert str(exc) == 'repr'
2526
assert repr(exc) == 'KeyError(repr,)'
27+
28+
# ImportError / ModuleNotFoundError
29+
exc = ImportError()
30+
assert exc.name is None
31+
assert exc.path is None
32+
assert exc.msg is None
33+
assert exc.args == ()
34+
35+
exc = ImportError('hello')
36+
assert exc.name is None
37+
assert exc.path is None
38+
assert exc.msg == 'hello'
39+
assert exc.args == ('hello',)
40+
41+
exc = ImportError('hello', name='name', path='path')
42+
assert exc.name == 'name'
43+
assert exc.path == 'path'
44+
assert exc.msg == 'hello'
45+
assert exc.args == ('hello',)

tests/snippets/import.py

+5
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@
2525
except ImportError:
2626
pass
2727

28+
try:
29+
import mymodule
30+
except ModuleNotFoundError as exc:
31+
assert exc.name == 'mymodule'
32+
2833

2934
test = __import__("import_target")
3035
assert test.X == import_target.X

vm/src/exceptions.rs

+34
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,35 @@ impl ExceptionZoo {
312312
}
313313
}
314314

315+
fn import_error_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
316+
// TODO: call super().__init__(*args) instead
317+
exception_init(vm, args.clone())?;
318+
319+
let exc_self = args.args[0].clone();
320+
vm.set_attr(
321+
&exc_self,
322+
"name",
323+
args.kwargs
324+
.get("name")
325+
.cloned()
326+
.unwrap_or_else(|| vm.get_none()),
327+
)?;
328+
vm.set_attr(
329+
&exc_self,
330+
"path",
331+
args.kwargs
332+
.get("path")
333+
.cloned()
334+
.unwrap_or_else(|| vm.get_none()),
335+
)?;
336+
vm.set_attr(
337+
&exc_self,
338+
"msg",
339+
args.args.get(1).cloned().unwrap_or_else(|| vm.get_none()),
340+
)?;
341+
Ok(vm.get_none())
342+
}
343+
315344
pub fn init(context: &PyContext) {
316345
let base_exception_type = &context.exceptions.base_exception_type;
317346
extend_class!(context, base_exception_type, {
@@ -323,4 +352,9 @@ pub fn init(context: &PyContext) {
323352
"__str__" => context.new_rustfunc(exception_str),
324353
"__repr__" => context.new_rustfunc(exception_repr),
325354
});
355+
356+
let import_error_type = &context.exceptions.import_error;
357+
extend_class!(context, import_error_type, {
358+
"__init__" => context.new_rustfunc(import_error_init)
359+
});
326360
}

0 commit comments

Comments
 (0)