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 (ie using defonce ) of a var which is marked as ^:dynamic ?


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.

链接地址: http://www.djcxy.com/p/64468.html

上一篇: 模拟其他用户时发生灾难性故障

下一篇: 对于defonce,^:dynamic有什么用处?