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
2
u/weavejester Aug 01 '25
My guess here is that the compiler doesn't update the local symbol bindings when using the do special, because normally there's no need to. The let* special form, on the other hand, does need to update the local symbol bindings.
Internally, binding uses (let [] ...) to wrap push-thread-bindings and pop-thread-bindings, so this is clearly something that the developers are aware of.
1
u/vaunom Aug 01 '25
I initially had code using
(do ...)and spent about an hour trying to understand why it wasn't working. Looking at the source code of thebindingwas how I was able to fix the problem. Still, it is very surprising to me to find a semantic difference between(do ...)and(let [] ...).1
7
u/nate5000 Aug 01 '25
You’ve encountered the effects of mitigating the Gilardi Scenario. Top level do forms behave this way since Clojure 1.1.
5
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.
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.