In clojure, how do I get the file name for the current namespace?

I am writing code that should store data about the current namespace. My code generates an ontology, and I need to assign the URIs that should persist between clojure calls. These URIs are automatically generated, so this is not just a case where code authors write them.

I thought of using a similar mechanism for how Emacs stores data; by creating some lisp forms and saving them in a file. Then you can evaluate them when you start clojure, and everyone will be happy. The problem with using tools like leningen is that these files are in the root directory.

I can build against standard conditional conventions, but I would rather get the data directly from clojure; I know that the compiler adds source location data to clojure; is there any way i can access this myself?

+6
source share
1 answer

If you are looking for a namespace that is currently executing code at runtime, you can simply look at the value of clojure.core/*ns* :

 user> (defn which-ns? [] (str *ns*)) user> (which-ns?) "user" user> (ns user2) user2> (which-ns?) "user2" 

If you are looking for a file in which var or namespace was defined, then the location of the source code that you are referencing is stored by the compiler as metadata in var when evaluating the form def :

 user> (defn foo [x] (inc x)) user> (meta #'foo) {:arglists ([x]), :ns #<Namespace user>, :name foo, :line 1, :file "NO_SOURCE_FILE"} 

"NO_SOURCE_FILE" is that you evaluate the form entered in the REPL. If you are evaluating code from a source file, then :file will indicate the path to the source file.

+12
source

All Articles