Mars
Mars

Reputation: 8854

How to require namespace inside function -main?

Suppose that in Leiningen project yo, I have these files:

foo.clj:

(ns yo.foo)
(def x 234.5)

bar.clj:

(ns yo.bar)
(def x -15)

And I have a main file (core.clj):

(ns yo.core)
(require '[yo.foo :as f])
(when (= f/x 234.5) (println "Succesfully required foo."))
(defn -main [& args]
  (println (require '[yo.bar :as b]))
  ;(when (= b/x -15) (println "Succesfully required bar."))
 )

When I enter "lein run" on the command line, I get this output:

Succesfully required foo.
nil

The first line tells me that I understand how to use the require function at the top level of a file. (Normally I would use :require in the ns statement.) The second line seems to indicate that I successfully required yo.bar.

However, when I uncomment the line containing when in -main, I get an exception: java.lang.RuntimeException: No such namespace: b, compiling:(yo/core.clj:6:9).

Is there a way to perform a require from inside a function? My goal is to pass the name of a namespace on the command line, and have that namespace loaded as a result. Is there another way to do this? (I already know how to access command line arguments from within -main.)

(The problem is not that I wrapped the require call with println. I get the same exception if the first line of -main says only (require '[yo.bar :as b]).)

(The title of this question makes it seem as if it's the same as mine, but the question and the answer don't address the problem of requiring a namespace from inside a function.)

Upvotes: 4

Views: 682

Answers (1)

Leon Grapenthin
Leon Grapenthin

Reputation: 9276

The require statement within the function -main is not invoked during compilation. Thus the compiler can't resolve the namespace b and complains.

Upvotes: 1

Related Questions