How to bypass print-method

137 views Asked by At

I have an application with a lot of large maps and other things, which are clumsy to read when printed, so I made a custom print function for them and set up print-method to call it, like this:

(defmethod print-method clojure.lang.PersistentArrayMap [v ^java.io.Writer w]
  (.write w (fstr1 v)))

Inside fstr1, how can I call the ordinary print-method if I determine that the map is not one of the kinds that require special treatment?

This answer suggests putting a :type in the metadata, since print-method dispatches on that. I've had some success with that, but I can't always control the metadata, so I'm hoping there's a way to "forward" to the previously defined print-method from within fstr1.


For reference, here's my current implementation of fstr1:

(defn fstr1 ^String [x]
  (cond
    (ubergraph? x)
      (fstr-ubergraph x)
    (map? x)
      (case (:type x)
        :move (fstr-move x)
        :workspace "(a workspace)"
        :bdx (fstr-bdx x)
        :rxn (fstr-rxn x)
        (apply str (strip-type x)))
    :else
      (apply str (strip-type x))))
1

There are 1 answers

0
Vebjorn Ljosa On

You can always rebind print-object and tuck the real print-object away so you can call it when appropriate:

user> (let [real-print-method print-method]
        (with-redefs [print-method (fn [v w]
                                     (if (and (map? v)
                                              (:foo v))
                                       (do
                                         (real-print-method "{:foo " w)
                                         (real-print-method (:foo v) w)
                                         (real-print-method " ...}" w))
                                       (real-print-method v w)))]
          (println {:foo 42 :bar 23} {:baz 11 :quux 0})))
{:foo 42 ...} {:baz 11, :quux 0}
nil
user>