You can switch to an existing namespace by evaluating (in-ns 'MY-NAMESPACE-NAME)
.
Here’s an example REPL session that creates a namespace myapp.some-ns
, defines a Var named x
in it,
moves back to the user
namespace, then moves again to myapp.some-ns
:
$ clj
Clojure 1.10.0
user=> (ns myapp.some-ns) ;;;; creating the namespace `myapp.some-ns`
nil
myapp.some-ns=> *ns* ;; where are we?
#object[clojure.lang.Namespace 0xacdb094 "myapp.some-ns"]
myapp.some-ns=> (def x 42) ;; defining `x`
#'myapp.some-ns/x
myapp.some-ns=> (in-ns 'user) ;;;; switching back to `user`
#object[clojure.lang.Namespace 0x4b45dcb8 "user"]
user=> *ns* ;; where are we?
#object[clojure.lang.Namespace 0x4b45dcb8 "user"]
user=> (in-ns 'myapp.some-ns) ;;;; ...switching back again to `myapp.some-ns`
#object[clojure.lang.Namespace 0xacdb094 "myapp.some-ns"]
myapp.some-ns=> *ns* ;; where are we?
#object[clojure.lang.Namespace 0xacdb094 "myapp.some-ns"]
myapp.some-ns=> x ;; `x` is still here!
42
What happens if you in-ns
to a namespace that has never been created?
You will see strange things happening. For instance, you will not be able to define
a function using defn
:
$ clj
Clojure 1.10.0
user=> (in-ns 'myapp.never-created)
#object[clojure.lang.Namespace 0x22356acd "myapp.never-created"]
myapp.never-created=> (defn say-hello [x] (println "Hello, " x "!"))
Syntax error compiling at (REPL:1:1).
Unable to resolve symbol: defn in this context
Explanation: in this situation, in-ns
creates the new namespace and switches to it like ns does,
but it does a little less work than ns,
because it does not automatically make available all the names defined in clojure.core
,
such as defn.
You can fix that by evaluating (clojure.core/refer-clojure)
:
myapp.never-created=> (clojure.core/refer-clojure)
nil
myapp.never-created=> (defn say-hello [x] (println "Hello, " x "!"))
#'myapp.never-created/say-hello
myapp.never-created=> (say-hello "Jane")
Hello, Jane !
nil
If you only use in-ns
to switch to namespaces that have already been created, you won’t have to deal with these subtleties.