diff --git a/tests/snippets/import.py b/tests/snippets/import.py index 1a5130269..0a36e6342 100644 --- a/tests/snippets/import.py +++ b/tests/snippets/import.py @@ -16,6 +16,12 @@ assert import_target.Y == aliased_other_func() assert STAR_IMPORT == '123' +try: + from import_target import func, unknown_name + raise AssertionError('`unknown_name` does not cause an exception') +except ImportError: + pass + # TODO: Once we can determine current directory, use that to construct this # path: #import sys diff --git a/vm/src/builtins.rs b/vm/src/builtins.rs index a08e70fb7..8b8c8690b 100644 --- a/vm/src/builtins.rs +++ b/vm/src/builtins.rs @@ -818,6 +818,7 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef { ctx.set_attr(&py_mod, "TypeError", ctx.exceptions.type_error.clone()); ctx.set_attr(&py_mod, "ValueError", ctx.exceptions.value_error.clone()); ctx.set_attr(&py_mod, "IndexError", ctx.exceptions.index_error.clone()); + ctx.set_attr(&py_mod, "ImportError", ctx.exceptions.import_error.clone()); py_mod } diff --git a/vm/src/import.rs b/vm/src/import.rs index f0f331c14..e560d3b18 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -71,11 +71,17 @@ pub fn import( let module = import_module(vm, current_path, module_name)?; // If we're importing a symbol, look it up and use it, otherwise construct a module and return // that - let obj = match symbol { - Some(symbol) => module.get_item(symbol).unwrap(), - None => module, - }; - Ok(obj) + if let Some(symbol) = symbol { + module.get_item(symbol).map_or_else( + || { + let import_error = vm.context().exceptions.import_error.clone(); + Err(vm.new_exception(import_error, format!("cannot import name '{}'", symbol))) + }, + |obj| Ok(obj), + ) + } else { + Ok(module) + } } fn find_source(vm: &VirtualMachine, current_path: PathBuf, name: &str) -> Result {