get a clojure function's code
Asked Answered
A

1

13

Is there a way in clojure to get a function's code after the function has been loaded?

Ie. without doing something like [untested]

(defmacro blat [x] `(do (def code ~(quote (mexpand-all x)))
                        ~x)))
(blat (defn func [abc] (...)))
Aboard answered 16/1, 2011 at 22:26 Comment(0)
P
8

You can get the source of a symbol using the clojure.repl/source function. However, this only works if the var for which the symbol resolves to is in a .clj file on the classpath. You can't, for example, do this:

user=> (defn foo [x] x)
#'user/foo
user=> (require 'clojure.repl)
nil
user=> (clojure.repl/source foo)
Source not found
nil
Practitioner answered 16/1, 2011 at 22:45 Comment(1)
hmm. (mexpand-all (read-string (source-fn 'foo))) is about what I wantAboard

© 2022 - 2024 — McMap. All rights reserved.