6

I am currently using the following which works - but it seems a bit of a cludge

(defn get-namespace
  [qualified-var]
  {:pre [(var? qualified-var)]}
  (the-ns
   (symbol
    (apply str (drop 2 (first (str/split (str qualified-var) #"/")))))))

ignoring the ugly string splitting (quick and dirty) is there a built in to do this?

Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76
beoliver
  • 5,579
  • 5
  • 36
  • 72

1 Answers1

3

The var's metadata contains a reference to its namespace under the :ns key. That would be the namespace in which the var is defined. The var's metadata can be accessed using the meta function. Putting it all together, we get (-> some-var meta :ns) and we can experiment a bit:

(def x "foo")
;; #'user/x
(-> #'x meta :ns)
;; #object[clojure.lang.Namespace 0x396bcdb0 "user"]
(-> #'clojure.core/map meta :ns)
;; #object[clojure.lang.Namespace 0x28412381 "clojure.core"]

A full example may look like this:

(defn var-namespace
  [qualified-var]
  {:pre [(var? qualified-var)]}
  (-> qualified-var meta :ns))
ez121sl
  • 2,371
  • 1
  • 21
  • 28