functionclojuremetadataclojure-contrib

How do I dynamically find metadata for a Clojure function?


Say I have the following code:

(defn ^{:graph-title "Function 1"} func-1
  [x]
  (do-something-with x))

(defn get-graph-title 
  [func]
  (str
    ((meta func) :graph-title))) 

I expect this to return "Function 1", but it returns nil. I think this stems from the following difference, which I don't totally comprehend:

(meta func-1)
=>  {:ns some-ns-info, :name func-1}
(meta #'func-1)
=>  {:ns some-ns-info, :name func-1, :graph-title "Function 1"}

Can someone explain this to me?


Solution

  • The metadata is attached to the var, not to the function.

    Thus, to get the graph title, you have to get the entry :graph-title from the meta of the var. How do you like your macros ?

    (defmacro get-graph-title
      [func]
      `(:graph-title (meta (var ~func))))
    
    (get-graph-title func-1)
    => "Function 1"