Some Practical Clojure Examples
← prev | next →     Top-level ToC     /namespaces.html     (printable version)

Namespaces contain maps of symbols to vars.

*ns*           ; This is the current namespace.
(class *ns*)   ;=> clojure.lang.Namespace
(ns-name *ns*) ;=> user (or whatever your curr namespace is)

When you write (def x 3), you’re updating the current namespace’s symbol-to-var mapping; you’re interning the var.

(ns-interns *ns*) ;=> A map of symbols to vars.

(def x 3)
(doseq [foo (ns-interns *ns*)] (println foo))
;; ...
;; [x #'user/x]
;; ...

(get (ns-interns *ns*) 'x)
;;=> #'user/x

;; Gives you *all* the mappings (not just intern mappings).
(ns-map *ns*)

In your source code files, you’ll almost always use the ns macro (described further below). In the repl however, you might use the following:

;; Create a new namespace (if it doesn't already exist) and return it:
(create-ns ' ; **not often used.**

;; Create a new namespace (if it doesn't exist) and move into it (set
;; `*ns*` to this namespace):
(in-ns '

;; Makes it so you can refer to `baz.moo/x` as simply `x`.
;; Brings in the raging hoards from baz.moo. Use at your peril.
(refer 'baz.moo)

clojure.core is automatically referred in for our convenience (clojure.core/refer-clojure will do this).

use is the same as require + refer.

;; Lets you type `abc/foo` instead of `aaa.bbb.ccc/foo`.
(alias 'abc 'aaa.bbb.ccc)

;; Locates aaa.bbb.ccc (aaa/bbb/ccc.clj), reads & evaluates it
;; (thus defining that namespace), and makes that namespace
;; available to your code.
(require 'aaa.bbb.ccc)
;; Now you can access things like `aaa.bbb.ccc/x`.

(require '[aaa.bbb.ccc :as abc]) ; access like `abc/x`.

1 The ns Macro

At the top of your .clj files, you’ll have something like:

  (:require [aaa.bbb.ccc :as abc]
            [clojure.string :as str])
  (:import [java.util ArrayMap

Note that :require makes it so you can access those namespaces; the :import just makes it so you can refer to those Java classes by their unqualified names.

See also