From 5c40f793a19244e8527c7921b9687cccfac76217 Mon Sep 17 00:00:00 2001 From: Simon Gomizelj Date: Mon, 5 Feb 2018 17:10:43 -0500 Subject: [PATCH] Support PEP 328 Add support for proper relative imports --- NEWS | 1 + hy/compiler.py | 11 +++++++++-- tests/native_tests/__init__.hy | 0 tests/native_tests/__init__.py | 3 +++ tests/native_tests/language.hy | 5 +++++ tests/resources/tlib.py | 3 +++ 6 files changed, 21 insertions(+), 2 deletions(-) delete mode 100644 tests/native_tests/__init__.hy create mode 100644 tests/native_tests/__init__.py diff --git a/NEWS b/NEWS index 2ca6d0f..932d8cf 100644 --- a/NEWS +++ b/NEWS @@ -27,6 +27,7 @@ Changes from 0.13.0 * new `doc` macro and `#doc` tag macro * support for PEP 492 with `fn/a`, `defn/a`, `with/a` and `for/a` * remove `def` + * support for relative imports (PEP 328) [ Bug Fixes ] * Numeric literals are no longer parsed as symbols when followed by a dot diff --git a/hy/compiler.py b/hy/compiler.py index c378b7d..ccacdce 100755 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -1156,10 +1156,17 @@ class HyASTCompiler(object): def _compile_import(expr, module, names=None, importer=asty.Import): if not names: names = [ast.alias(name=ast_str(module), asname=None)] + + ast_module = ast_str(module) + module = ast_module.lstrip(".") + level = len(ast_module) - len(module) + if not module: + module = None + ret = importer(expr, - module=ast_str(module), + module=module, names=names, - level=0) + level=level) return Result() + ret expr.pop(0) # index diff --git a/tests/native_tests/__init__.hy b/tests/native_tests/__init__.hy deleted file mode 100644 index e69de29..0000000 diff --git a/tests/native_tests/__init__.py b/tests/native_tests/__init__.py new file mode 100644 index 0000000..0ff21ce --- /dev/null +++ b/tests/native_tests/__init__.py @@ -0,0 +1,3 @@ +# Note that __init__.py is intentional so pytest (more specifically py.path) +# will detect us as a Python package. There's logic there that involves looking +# specifically for this file. diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index 3ef9be3..94669b8 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -1812,3 +1812,8 @@ macros() (defn f4 [[a b]] "not a docstring") (assert (none? (. f4 __doc__))) (assert (= (f4 [1 2]) "not a docstring"))) + +(defn test-relative-import [] + "Make sure relative imports work properly" + (import [..resources [tlib]])) + (assert (= (tlib.*secret-message* "Hello World"))) diff --git a/tests/resources/tlib.py b/tests/resources/tlib.py index a51029b..e774e3c 100644 --- a/tests/resources/tlib.py +++ b/tests/resources/tlib.py @@ -2,6 +2,9 @@ from hy.macros import macro from hy import HyList, HyInteger +SECRET_MESSAGE = "Hello World" + + @macro("qplah") def tmac(ETname, *tree): return HyList((HyInteger(8), ) + tree)