Skip to content

Commit

Permalink
Merge pull request #2015 from peaceamongworlds/fix_relative_paths_req…
Browse files Browse the repository at this point in the history
…uire

Fixed relative import for `require` and added tests
  • Loading branch information
Kodiologist authored Mar 27, 2021
2 parents 9733a3d + 6f01d05 commit 02559d0
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions NEWS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Bug Fixes
* Fixed namespace pollution caused by automatic imports of Hy builtins and macros.
* Fixed Hy model objects sometimes not being in scope.
* Fixed `doc` sometimes failing to find builtin macros.
* `require` now works with relative imports.

Misc. Improvements
------------------------------
Expand Down
12 changes: 11 additions & 1 deletion hy/macros.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,17 @@ def require(source_module, target_module, assignments, prefix=""):

if not inspect.ismodule(source_module):
try:
source_module = importlib.import_module(source_module)
if source_module.startswith("."):
source_dirs = source_module.split(".")
target_dirs = (getattr(target_module, "__name__", target_module)
.split("."))
while source_dirs and target_dirs and source_dirs[0] == "":
source_dirs.pop(0)
target_dirs.pop()
package = ".".join(target_dirs + source_dirs[:-1])
else:
package = None
source_module = importlib.import_module(source_module, package)
except ImportError as e:
reraise(HyRequireError, HyRequireError(e.args[0]), None)

Expand Down
7 changes: 7 additions & 0 deletions tests/native_tests/language.hy
Original file line number Diff line number Diff line change
Expand Up @@ -1478,6 +1478,13 @@ cee\"} dee" "ey bee\ncee dee"))
(rev (.append x 1) (.append x 2) (.append x 3))
(assert (= x [3 2 1])))

(defn test-relative-require []
(require [..resources.macros [nonlocal-test-macro]])
(assert (in "nonlocal_test_macro" __macros__))

(require [.native-macros [rev]])
(assert (in "rev" __macros__)))


(defn test-encoding-nightmares []
"NATIVE: test unicode encoding escaping crazybits"
Expand Down

0 comments on commit 02559d0

Please sign in to comment.