liveBook · Manning

Source-fn

As explained in Clojure: The Essential Reference

source-fn is a Clojure function that returns the original source text for a public definition as a string.

source-fn is the function form of source: pass it a symbol naming a public definition, and it returns that definition's original source text as a string instead of printing it. section 22.3

Capture source as data

(require '[clojure.repl :refer [source-fn]]) (source-fn 'not-empty) ;; "(defn not-empty\n ...\n [coll] (when (seq coll) coll))" (println *1) ;; prints the captured definition section 22.3

(require '[clojure.repl :refer [source-fn]])
(source-fn 'not-empty) ; #1
;; "(defn not-empty\n  \"If coll is empty, returns nil, else coll\"\n  ; #2
;; {:added \"1.0\"\n   :static true}\n  [coll] (when (seq coll) coll))"

(println *1) ; #3
;; (defn not-empty
;;   "If coll is empty, returns nil, else coll"
;;   {:added "1.0"
;;    :static true}
;;   [coll] (when (seq coll) coll))

Inspect the complete returned string, including the definition, docstring, metadata, and argument form. section 22.3

Use source-fn when source needs to be captured, transformed, or inspected programmatically. Special forms and Java methods or classes do not provide retrievable source in this way. section 22.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines the symbol-to-string contract and demonstrates output, while deferring reader internals and source-loading limitations.
Examples
Demonstrates retrieving not-empty source, printing the returned string, and inspecting its definition metadata.
What it assumes
Assumes familiarity with symbols and requiring clojure.repl, while demonstrating the function's basic contract directly.
What you can do after
Apply it via clojure.repl to capture a public definition's original source without sending output to standard output.
How it connects
Connects source-fn with source, public definitions, symbols, and the Clojure reader.

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.