Skip to content

How do I prevent macros from polluting the global namespace via import? #2394

Answered by Kodiologist
glyh asked this question in Q&A
Discussion options

You must be logged in to vote

import has to go at the top of the file

Not so. Python allows import wherever a statement is allowed, so long as it's not import *.

The way to import in a macro expansion is to use a gensym:

(defmacro m []
  (setv math (hy.gensym))
  `(do
    (import math :as ~math)
    ((. ~math sqrt) 2)))

(print (m))   ; => 1.4142135623730951
(print math)  ; => NameError: name 'math' is not defined

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@glyh
Comment options

@Kodiologist
Comment options

@glyh
Comment options

Answer selected by glyh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants