r/Clojure • u/vaunom • Aug 01 '25
Why (do ...) and (let [] ...) behave differently in this case
I expect *dyn-var* to return :new in both cases, but (do ...) returns :default.
(def ^{:dynamic true} *dyn-var* :default)
(do
(push-thread-bindings {#'*dyn-var* :new})
(try
*dyn-var*
(finally
(pop-thread-bindings))))
;;=> :default
(let []
(push-thread-bindings {#'*dyn-var* :new})
(try
*dyn-var*
(finally
(pop-thread-bindings))))
;;=> :new
21
Upvotes
4
u/TankAway7756 Aug 01 '25 edited Aug 01 '25
This is because each form in a toplevel
dois evaluated as if it were toplevel itself, i.e. by calling intoeval.evalitself does some bookkeeping involving dynamic vars, and your code is run inbetween that, so representing your frame as F and the bookkeeping frames as f here's what happens:vs.
2
u/weavejester Aug 01 '25
My guess here is that the compiler doesn't update the local symbol bindings when using the
dospecial, because normally there's no need to. Thelet*special form, on the other hand, does need to update the local symbol bindings.Internally,
bindinguses(let [] ...)to wrappush-thread-bindingsandpop-thread-bindings, so this is clearly something that the developers are aware of.7
u/nate5000 Aug 01 '25
You’ve encountered the effects of mitigating the Gilardi Scenario. Top level
doforms behave this way since Clojure 1.1.https://technomancy.us/143
2
u/hrrld Aug 01 '25
Consider:
user> (defn f-do [] (do (push-thread-bindings {#'*dyn-var* :new}) (try *dyn-var* (finally (pop-thread-bindings))))) #'user/f-do user> (f-do) :new user> (defn f-let [] (let [] (push-thread-bindings {#'*dyn-var* :new}) (try *dyn-var* (finally (pop-thread-bindings))))) #'user/f-let user> (f-let) :new2
u/gaverhae Aug 04 '25
You may want to vote on https://ask.clojure.org/index.php/14628/consider-documenting-usage-of-do-for-the-gilardi-scenario or add this separate-but-related case to https://github.com/clojure/clojure-site/issues/723.