Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of ^:dynamic on a defonce?

Looking at clojure.test source code, I spotted the following:

(defonce ^:dynamic
  ^{:doc "True by default.  If set to false, no test functions will
   be created by deftest, set-test, or with-test.  Use this to omit
   tests when compiling or loading production code."
    :added "1.1"}
  *load-tests* true)

Is there any benefit or reason behind preventing redefinition (i.e. using defonce) of a var which is marked as ^:dynamic?

like image 445
skuro Avatar asked Oct 09 '12 10:10

skuro


1 Answers

defonce doesn't prevent redefinition in general, but only when one reloads the file. This is useful typically when the var is maintaining some sort of state or context. I believe the usage of defonce here, could be an artifact from development of the library, where the developer needs to reload the file many times during development while still wanting to retain the same value.

Since the var is not pointing to a ref, but a direct var, using ^:dynamic is the right choice. Now the code can use set! or binding to change the value in a thread-local way.

like image 161
bmillare Avatar answered Sep 21 '22 00:09

bmillare