From f8db0f1c94b818122a9ccee9ad09e6806147c2f9 Mon Sep 17 00:00:00 2001 From: lausek Date: Tue, 5 Feb 2019 15:42:39 +0100 Subject: [PATCH 1/2] raise ImportError in import list --- tests/snippets/import.py | 6 ++++++ vm/src/import.rs | 16 +++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/tests/snippets/import.py b/tests/snippets/import.py index 1a5130269..2699002d0 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: + pass + # TODO: Once we can determine current directory, use that to construct this # path: #import sys 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 { From f4af59916793b1435f278db1f1a233d12e9d03a8 Mon Sep 17 00:00:00 2001 From: lausek Date: Tue, 5 Feb 2019 17:41:05 +0100 Subject: [PATCH 2/2] added ImportError as builtin --- tests/snippets/import.py | 2 +- vm/src/builtins.rs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/snippets/import.py b/tests/snippets/import.py index 2699002d0..0a36e6342 100644 --- a/tests/snippets/import.py +++ b/tests/snippets/import.py @@ -19,7 +19,7 @@ assert STAR_IMPORT == '123' try: from import_target import func, unknown_name raise AssertionError('`unknown_name` does not cause an exception') -except: +except ImportError: pass # TODO: Once we can determine current directory, use that to construct this 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 }