1
votes

There are two macros binding and with-bindings to redefine dynamic vars. However both seem to have the utility, what is the difference between them ?

;; binding
(def :^dynamic a 10)
(binding [a 20] a) ;; => 20
a ;; => 10

;; with-bindings
(with-bindings {#'a 20}
  a) ;; => 20
a ;; => 10

both of them are changing the per thread dynamic scope, and resetting it to the root binding after the lexical scope is over.

1
This answer (stackoverflow.com/a/18495325/2229272) to a different questions offers a theory "... with-bindings is, as far as I can tell, primarily useful as a helper to pass bindings from another context by using a map returned by get-thread-bindings. The similar function binding would be more typical when not importing bindings." - jas

1 Answers

2
votes

The underlying implementation of both is pretty much identical:

  • push thread bindings (using the bindings supplied)
  • try the body
  • finally pop thread bindings

binding was added in Clojure 1.0 and with-bindings in 1.1. I don't see the latter used in any code tho', just the former.