Merge pull request #332 from lausek/imports

raise ImportError in import list
This commit is contained in:
Windel Bouwman
2019-02-05 18:25:41 +01:00
committed by GitHub
3 changed files with 18 additions and 5 deletions

View File

@@ -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

View File

@@ -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
}

View File

@@ -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<PathBuf, String> {