16 Vars and Namespaces

 

Before introducing the functions and macros in this section, it’s useful to refresh a few definitions about Clojure namespaces, vars and local bindings.

16.1  Namespaces

  • A "namespace" is an instance of clojure.lang.Namespace class and is essentially a container for other objects. It contains a mapping table and an alias table.
  • The "mapping table" is a dictionary associated with each namespace. It contains a mapping between Clojure symbols and objects such as vars or classes. Functions like intern or def adds items into the table, while ns-map shows its content.
  • The "alias table" is another type of dictionary associated with a namespace. It contains relationships with other namespaces, using a symbol as key and a namespace name as value. Items can be added to the alias table with :as during namespace creation or with the alias function. ns-aliases shows its content.
  • Once a namespace is created, a reference is added to the "global namespace repository". This is a static map inside the clojure.lang.Namespace class itself. It derives that namespaces are "global", that is, the running process doesn’t need to hold an explicit namespace reference to keep them alive (from the garbage collector perspective).

16.2  Libraries

16.2.1  Vars and Bindings

16.3  def, declare, intern and defonce

16.3.1  def

16.3.2  declare

16.3.3  intern

16.3.4  defonce

16.4  var, find-var and resolve

16.4.1  var

16.4.2  find-var

16.4.3  resolve and ns-resolve

resolve

ns-resolve

16.4.4  clojure.repl/dir-fn and clojure.repl/dir

16.4.5  bound? and thread-bound?

16.5  alter-var-root and with-redefs

16.5.1  alter-var-root