Clojure:能否在指定命名空间上下文执行load-file以避免重复导包?
Solution: Force
load-file to Execute in Your Reader Namespace The root issue here is that load-file runs code in the calling namespace by default—so when you invoke load-definition-and-apply from my-project.processing, the ml/explode reference in whatever.clj tries to resolve against that namespace (which doesn't have the ml alias imported).
To fix this without modifying whatever.clj or requiring dependencies in every calling namespace, you can temporarily bind the *ns* dynamic var to your my-project.reader namespace when loading the file. This forces the loaded code to execute in the context where ml is already aliased, regardless of where you call the function from.
Modified Code for my-project.reader
(ns my-project.reader (:require [my-lib.core :as ml])) (defn load-definition-and-apply [a b] (let [{:keys [my-fn]} ;; Bind *ns* to this namespace so load-file uses our aliases (binding [*ns* (find-ns 'my-project.reader)] (load-file "whatever.clj"))] (my-fn a b)))
How This Works
- The
bindingform temporarily overrides the value of*ns*(the current namespace) to point tomy-project.readerwhileload-fileruns. - Since
my-project.readeralready hasmy-lib.corealiased asml, theml/explodecall inwhatever.cljresolves correctly. - Once
load-filecompletes, the original value of*ns*is restored automatically (thanks to Clojure's dynamic binding semantics), so you don't have to worry about side effects on the calling namespace.
Key Benefits
- No changes needed to
whatever.clj—keeps user-facing files clean and simple. - All dependency management stays centralized in
my-project.reader; calling namespaces likemy-project.processingdon't need to import any of the dependencies used by the loaded file. - This pattern scales to multiple dependencies: just add all required
:requireclauses inmy-project.reader, and the loaded file will have access to all of them.
内容的提问来源于stack exchange,提问作者Joseph Yourine
相关产品推荐
相关产品推荐

