8

I am writing some code which needs to store data about the current namespace. My code is generating an ontology, and I need to assign URIs that need to persist between clojure invocations. These URIs are automatically generated, so it's not just a case of the code authors writing them.

I thought to use a similar mechanism to the way Emacs stores data; by generating some lisp forms and saving them in a file. These can then be evaluated when clojure starts and everyone is happy. The problem when using tools like leningen, these files will end up in the root directory.

I can build against standard directory conventions, but I'd prefer to get the data straight from clojure; I know the compiler adds source location data to clojure; is there a way that I can access this myself?

2
  • Can you explain in more details why you don't want to keep "saved" data in root directory? You can read it and evaluate from clojure. Dec 19, 2012 at 15:42
  • The data that I keep saved will be partly human readable. It makes more sense to me, to keep it with the file to which it refers. It will be versioned along with it.
    – Phil Lord
    Dec 19, 2012 at 20:02

1 Answer 1

18

If you're looking for the namespace in which code is currently executing at runtime, then 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're looking for the file in which a var or namespace was defined, then the source code location you're referring to is stored by the compiler as metadata on the var when it evaluates a def form:

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

The "NO_SOURCE_FILE" is because you're evaluating a form entered in the REPL. If you evaluate code from a source file, then :file will point to the pathname of the source file.

2
  • Hmmm. This made me wonder whether there is any metadata on the name space itself, but the namespace doesn't actually bind a symbol. I think though that you have made a good point -- what ever I do, it's likely to fail if I run code in a REPL. A namespace doesn't map directly to a file, even if it appears to.
    – Phil Lord
    Dec 19, 2012 at 20:11
  • You can get from a symbol to a namespace using (the-ns 'clojure.core), and you can get/set metadata on the ns... but the compiler doesn't appear to add the source file as metadata to the ns.
    – Alex
    Dec 19, 2012 at 20:19

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.