Programming Languages – When is Dynamic Scoping Useful?

accessfunctionsprogramming-languagesscopevariables

With dynamic scoping, a callee can access the variables of its caller. Pseudo C code:

void foo()
{
    print(x);
}

void bar()
{
    int x = 42;
    foo();
}

Since I have never programmed in a language that supports dynamic scoping, I wonder what some real world use cases for dynamic scoping would be.

Best Answer

A very useful application of dynamic scoping is for passing contextual parameters without having to add new parameters explicitly to every function in a call stack

For example, Clojure supports dynamic scoping via binding, which can be used to temporarily reassign the value of *out* for printing. If you re-bind *out* then every call to print within the dynamic scope of the binding will print to your new output stream. Very useful if, for example, you want to redirect all printed output to some kind of debugging log.

Example: in the code below, the do-stuff function will print to the debug output rather than standard out, but note that I didn't need to add an output parameter to do-stuff to enable this....

(defn do-stuff [] 
  (do-other-stuff)
  (print "stuff done!"))

(binding [*out* my-debug-output-writer]
  (do-stuff))

Note that Clojure's bindings are also thread-local, so you don't have an issue with concurrent usage of this capability. This makes bindings considerably safer than (ab)using global variables for the same purpose.