liveBook · Manning

Namespace

As explained in Clojure: The Essential Reference

A namespace is a Clojure scope that organizes and qualifies names such as functions and variables.

A Clojure namespace organizes names used to access functions, vars, and classes. It is an instance of clojure.lang.Namespace with two tables: one for symbol mappings and one for aliases. section 16.0

The two tables serve different purposes:

  • The mapping table associates symbols with objects such as vars or classes. def and intern add mappings; ns-map displays them. section 16.0
  • The alias table associates short symbols with other namespace names. :as or alias adds an alias; ns-aliases displays aliases. section 16.0

Names in clojure.core are available without an explicit reference. Other standard-library namespaces include clojure.string; a qualified name such as clojure.string/upper-case may be usable directly, while some namespaces must first be loaded with require. section 1.4

(def user-ns-mapping (ns-map 'user))  ; #1
(def lookup-var ('+ user-ns-mapping)) ; #2
(lookup-var 1 1) ; #3
;; 2

The listing reads the user namespace’s mappings with ns-map, retrieves the var mapped to +, and calls it with 1 and 1 to produce 2. section 16.0

A namespace is not necessarily a loaded library. A library is a source file named for its namespace declaration: require loads it and its transitive dependencies, while create-ns can create a namespace without a library. Created namespaces are held in a global repository for the running process. section 16.0 section 16.0

How Clojure: The Essential Reference covers it

How deep it goes
Defines mapping and alias tables and identifies the global repository, without elaborating garbage-collector mechanics.
Examples
Uses clojure.string/upper-case and an ns-map lookup that retrieves and calls the var mapped to +.
What it assumes
Refreshes namespace, var, and local-binding definitions before related functions and macros, assuming some prior exposure.
What you can do after
Diagnose/debug with it: inspect mappings using ns-map, inspect aliases using ns-aliases, and distinguish namespaces from loaded libraries.
How it connects
Connects symbols and vars to mapping tables, aliases to other namespaces, and require to libraries.

Also explained in

Compare how 20 books explain namespace →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.