ClojureDocs

Nav

Namespaces

in-ns

clojure.core

Available since 1.0
  • (in-ns name)
Sets *ns* to the namespace named by the symbol, creating it if needed.
2 Examples
;; Let's create new namespace, create new variable in it, then access it from
;; another namespace

;; create the namespace and switch to it
(in-ns 'first-namespace)
;;=> #<Namespace first-namespace>

;; create a variable and check it
;; first-namespace=> 
(def my-var "some value")
;;=> #'first-namespace/my-var

;; first-namespace=> 
my-var
;;=> "some value"

;; create another namespace and switch to this one
;; first-namespace=> 
(in-ns 'second-namespace)
;;=> #<Namespace second-namespace>

;; use variable from the other namespace here
;; second-namespace=> 
first-namespace/my-var
;;=> "some value"

;; in-ns works within top-level forms (e.g. the compiler or the REPL)
;; It may fail when called within a function at runtime because *ns* is a Var
;; and unless there are thread-local bindings for *ns*, it cannot be set!
second.namespace=> (defn swap-ns! [ns-name] (clojure.core/in-ns ns-name))
;; #'second.namespace/swap-ns!

second.namespace=> (swap-ns! 'other.ns)
;; #namespace[other.ns]

;; Later, at runtime...
;; Throws IllegalStateException("Can't change/establish root binding of: *ns* with set")
;; Remember, *ns* is a root var and in-ns calls set!, which only works after
;; someone somewhere calls the binding macro (or Java equivalent)
(defn -main
  [& args]
  (println *ns*)
  (second.namespace/swap-ns! 'arbitrary-namespace))
;; prints #namespace[clojure.core] and then will crash
;; The "in-ns" function works almost the same as "ns", but does not load
;; clojure.core 

;; user=>
(in-ns 'my-namespace)
;;=> #<Namespace my-namespace>

;; the function clojure.core/inc won't just work
;; my-namespace=> 
(inc 1)
;; java.lang.Exception: Unable to resolve symbol: inc in this context
;; (NO_SOURCE_FILE:15)

;; my-namespace=>
(clojure.core/inc 1)
;;=> 2
See Also

Sets *ns* to the namespace named by name (unevaluated), creating it if needed. references can be ...

Added by frangio
0 Notes
No notes for in-ns