切换命名空间时保留变量

Keep variables when switching namespace

我正在使用以下片段创建命名空间,将当前命名空间中给定的符号列表及其值注入新命名空间并切换到新命名空间:

(defn in-ns-with-vars
  "Switch to a new namespace (creating it if necessary) and 
   inject the given symbols into the new namespace
   with the values they resolve to in the current namespace."
  [new-ns-symbol & symbols-to-inject]
  (let [n (create-ns new-ns-symbol)
    current-value-of (fn [v] @(ns-resolve (the-ns *ns*) v))]
    (do
      (doseq [v symbols-to-inject]
        (intern new-ns-symbol v (current-value-of v)))
      (in-ns new-ns-symbol)
      (clojure.core/refer 'clojure.core))))

是否有现成的机制来实现这一点?由于在脚本上下文中使用,当前(初始)名称空间是静态未知的,因此我无法静态引用它。

您可以使用 aliasrefer 和捕获的运行时符号 *ns* 来使绑定在新创建的命名空间。

user=> ((juxt identity type) (.name *ns*))
[user clojure.lang.Symbol]

potemkin 库中的 import-vars 函数可以为您执行此操作(在使用 *ns* 引用您的原始命名空间之后)。