liveBook · Manning

Binding

As explained in Clojure: The Essential Reference

with-bindings is a Clojure macro or function that establishes thread-local bindings from explicit var objects and values.

Binding establishes temporary thread-local values for dynamic vars while leaving their root bindings unchanged. It lets related functions share request state without threading an extra parameter through every call. section 16.4

Use binding when:

  • A request needs shared tracing or debugging state without changing function signatures. section 16.4
  • Output must be redirected temporarily to another stream, writer, or captured string. section 23.2 section 18.2
  • A new thread must receive the current bindings; wrap its function with bound-fn or bound-fn* because ordinary thread creation does not propagate them. section 16.4

Collecting request traces

With a dynamic *trace* var, `(binding [*trace* []] ...)` provides an empty vector for the request. Nested functions append messages, and the enclosing form can inspect the resulting trace while the request returns 3.

Thread propagation

`(binding [*debug* true] ...)` does not make a separately started thread see the value. `(bound-fn* #(debug ...))` propagates the binding and prints the debugging message.

How Clojure: The Essential Reference covers it

How deep it goes
Defines thread-local behavior, examples, and propagation limits, while deferring low-level push and pop primitives.
Examples
Uses request tracing, debugging across threads, stream redirection, file output, and captured strings.
What it assumes
Assumes familiarity with Clojure vars and dynamic variables while demonstrating their thread-local behavior through concrete examples.
What you can do after
Apply it via Clojure's binding form to share temporary dynamic state or redirect output within a thread.
How it connects
Connects dynamic variables with namespaces, standard streams, thread propagation, and output formatting functions.

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.