Lexical and Dynamic Scope Usage

Do you keep forgetting the difference between lexical and dynamic scoping? Perhaps it helps to think about when you would pick one over the other.

A rifle scope which has absolutely nothing to do with scopes in programming languages ;-) But it looks really cool.

In programming languages we frequently talk about whether variables have lexical or dynamic scope.

However for some reason lexical and dynamic scope is one of those things I keep having to look up, because I always forget it. I am sure I am not alone, so this is an attempt at coming up with examples and associations which will help you remember.

http://mileno.provecracing.com/hxm/video-vichentsa-v-askoli-v-yt2-1fuf-11.php
https://cartaodosus.info/video.php?video=videos-Lamontville-Golden-Arrows-Mamelodi-Sundowns-v-en-gb-1ffc-14.php
http://mid.actiup.com/ktb/videos-brescia-v-reggio-audace-v-it-it-1upn2-13.php
http://mileno.provecracing.com/hxm/videos-vichentsa-v-askoli-v-yt2-1rtf-2.php
http://amik.closa.com/njb/Video-urbs-reggina-v-cittadella-v-it-it-1tzu2-3.php
http://mid.actiup.com/ktb/video-brescia-v-reggio-audace-v-it-it-1prl2-8.php
https://cartaodosus.info/video.php?video=video-Lamontville-Golden-Arrows-Mamelodi-Sundowns-v-en-gb-1qlg-1.php
http://mileno.provecracing.com/hxm/videos-vichentsa-v-askoli-v-yt2-1jto-16.php
http://mileno.provecracing.com/hxm/v-ideos-vichentsa-v-askoli-v-yt2-1oxc-11.php
https://cartaodosus.info/video.php?video=Video-Lamontville-Golden-Arrows-Mamelodi-Sundowns-v-en-gb-1fvh-14.php
http://amik.closa.com/njb/Video-urbs-reggina-v-cittadella-v-it-it-1fgy2-11.php
http://mid.actiup.com/ktb/videos-brescia-v-reggio-audace-v-it-it-1tbe-1.php
https://cartaodosus.info/video.php?video=Video-Baroka-Supersport-United-v-en-gb-1zsa-14.php
http://amik.closa.com/njb/videos-urbs-reggina-v-cittadella-v-it-it-1ogi2-6.php
http://mileno.provecracing.com/hxm/Video-vichentsa-v-askoli-v-yt2-1dxi-18.php
http://amik.closa.com/njb/videos-urbs-reggina-v-cittadella-v-it-it-1akl-3.php
http://mileno.provecracing.com/hxm/v-ideos-NK-Osijek-sibenik-v-en-gb-1tii-18.php
https://cartaodosus.info/video.php?video=videos-Baroka-Supersport-United-v-en-gb-1txv-8.php
http://mid.actiup.com/ktb/v-ideos-yeni-malatyaspor-v-kasimpasa-v-tr-tr-1ahf-16.php
https://test.activesilicon.com/xrp/Video-Al-Fehaheel-Al-Tadamon-SC-v-en-gb-1rln-9.php
http://mileno.provecracing.com/hxm/videos-NK-Osijek-sibenik-v-en-gb-1mvj-13.php
https://cartaodosus.info/video.php?video=v-ideos-Baroka-Supersport-United-v-en-gb-1kcg-5.php
http://great.gruposio.es/pkm/videos-Al-Fehaheel-Al-Tadamon-SC-v-en-gb-1kue-4.php
http://mid.actiup.com/ktb/videos-yeni-malatyaspor-v-kasimpasa-v-tr-tr-1ymt-7.php
http://amik.closa.com/njb/video-urbs-reggina-v-cittadella-v-it-it-1ccq-15.php
http://mileno.provecracing.com/hxm/videos-NK-Osijek-sibenik-v-en-gb-1ljx-13.php
http://mid.actiup.com/ktb/Video-yeni-malatyaspor-v-kasimpasa-v-tr-tr-1won-15.php
http://amik.closa.com/njb/videos-Reggina-Cittadella-v-en-gb-1onl-.php
http://mileno.provecracing.com/hxm/v-ideos-lechche-v-piza-v-yt2-1axi-11.php
http://gd.vidrio.org/qez/videos-Knockbreda-Loughgall-v-en-gb-1jij-15.php
https://test.activesilicon.com/xrp/Video-US-Monastir-US-Ben-Guerdane-v-en-gb-1xnd-9.php
https://cartaodosus.info/video.php?video=Video-kristal-pelas-v-rpul-v-yt2-1uki-12.php
http://mid.actiup.com/ktb/v-ideos-yeni-malatyaspor-v-kasimpasa-v-tr-tr-1txk-7.php
http://mid.actiup.com/ktb/video-yeni-malatyaspor-v-kasimpasa-v-tr-tr-1rbw-10.php
http://amik.closa.com/njb/videos-Reggina-Cittadella-v-en-gb-1kzq-13.php
https://cartaodosus.info/video.php?video=Video-kristal-pelas-v-rpul-v-yt2-1mya-10.php
http://mileno.provecracing.com/hxm/v-ideos-lechche-v-piza-v-yt2-1dkd-15.php
http://amik.closa.com/njb/Video-Reggina-Cittadella-v-en-gb-1mcw-14.php
https://cartaodosus.info/video.php?video=v-ideos-kristal-pelas-v-rpul-v-yt2-1wvi-19.php
http://mileno.provecracing.com/hxm/Video-lechche-v-piza-v-yt2-1ozx-8.php
http://mid.actiup.com/ktb/videos-deportes-copiapo-v-barnechea-v-es-cl-1scd2-17.php
http://amik.closa.com/njb/videos-De-Graafschap-Jong-FC-Utrecht-v-en-gb-1bko-.php
https://test.activesilicon.com/xrp/v-ideos-US-Monastir-US-Ben-Guerdane-v-en-gb-1djw-18.php
http://mid.actiup.com/ktb/video-deportes-copiapo-v-barnechea-v-es-cl-1rbd2-9.php
https://cartaodosus.info/video.php?video=v-ideos-kristal-pelas-v-rpul-v-yt2-1qny-6.php
http://mileno.provecracing.com/hxm/Video-lechche-v-piza-v-yt2-1hrs-15.php
http://amik.closa.com/njb/v-ideos-De-Graafschap-Jong-FC-Utrecht-v-en-gb-1tcb-18.php
http://great.gruposio.es/pkm/videos-Al-Fehaheel-Al-Tadamon-SC-v-en-gb-1xky-16.php
http://mid.actiup.com/ktb/Video-deportes-copiapo-v-barnechea-v-es-cl-1dqj-11.php
http://mileno.provecracing.com/hxm/videos-lechche-v-piza-v-yt2-1sqx-13.php
https://cartaodosus.info/video.php?video=videos-kristal-pelas-v-rpul-v-yt2-1iqp-9.php
http://mid.actiup.com/ktb/Video-deportes-copiapo-v-barnechea-v-es-cl-1vqv-4.php
http://mileno.provecracing.com/hxm/v-ideos-FC-Fredericia-HB-Koge-v-en-gb-1mdd-13.php
http://amik.closa.com/njb/v-ideos-De-Graafschap-Jong-FC-Utrecht-v-en-gb-1rlu-18.php
https://cartaodosus.info/video.php?video=v-ideos-JS-Saoura-USM-Bel-Abbes-v-en-gb-1hxw-9.php
http://mid.actiup.com/ktb/Video-deportes-copiapo-v-barnechea-v-es-cl-1smt2-12.php
http://mileno.provecracing.com/hxm/v-ideos-FC-Fredericia-HB-Koge-v-en-gb-1utk-18.php
https://test.activesilicon.com/xrp/v-ideos-US-Monastir-US-Ben-Guerdane-v-en-gb-1gwh-15.php
https://cartaodosus.info/video.php?video=v-ideos-JS-Saoura-USM-Bel-Abbes-v-en-gb-1ded-4.php
http://mileno.provecracing.com/hxm/Video-FC-Fredericia-HB-Koge-v-en-gb-1tac-11.php
http://great.gruposio.es/pkm/videos-US-Monastir-US-Ben-Guerdane-v-en-gb-1bqj-.php
https://cartaodosus.info/video.php?video=v-ideos-JS-Saoura-USM-Bel-Abbes-v-en-gb-1ouj-6.php
https://cartaodosus.info/video.php?video=videos-Belouizdad-NA-Hussein-Dey-v-en-gb-1kqy-6.php
http://great.gruposio.es/pkm/v-ideos-US-Monastir-US-Ben-Guerdane-v-en-gb-1tuu-17.php
http://amik.closa.com/unx/video-Hapoel-Haifa-Hapoel-Kfar-Saba-v-en-gb-sbn-.php
https://cartaodosus.info/video.php?video=v-ideos-Belouizdad-NA-Hussein-Dey-v-en-gb-1ejy-6.php
https://cartaodosus.info/video.php?video=Video-Belouizdad-NA-Hussein-Dey-v-en-gb-1wif-6.php
http://amik.closa.com/unx/video-Hapoel-Haifa-Hapoel-Kfar-Saba-v-en-gb-owc-.php
https://cartaodosus.info/video.php?video=v-ideos-US-Biskra-Paradou-AC-v-en-gb-1gek-6.php
http://amik.closa.com/unx/v-ideos-Hapoel-Haifa-Hapoel-Kfar-Saba-v-en-gb-ocl-.php
http://mid.actiup.com/ktb/v-ideos-Al-Fehaheel-Al-Tadamon-SC-v-en-gb-1tzi-12.php
https://test.activesilicon.com/xrp/videos-Birkirkara-Gzira-United-v-en-gb-1jjf-15.php
https://cartaodosus.info/video.php?video=videos-US-Biskra-Paradou-AC-v-en-gb-1rqi-6.php
http://great.gruposio.es/pkm/Video-US-Monastir-US-Ben-Guerdane-v-en-gb-1zyd-7.php
https://cartaodosus.info/video.php?video=video-US-Biskra-Paradou-AC-v-en-gb-1oou-15.php
https://cartaodosus.info/video.php?video=Video-Gasogi-United-Rwanda-Police-FC-v-en-gb-1msm-15.php
http://gd.vidrio.org/qez/videos-Knockbreda-Loughgall-v-en-gb-1iyw-1.php
http://amik.closa.com/unx/videos-Jablonec-Dynamo-ceske-Budejovice-v-en-gb-biv-.php
https://cartaodosus.info/video.php?video=video-Gasogi-United-Rwanda-Police-FC-v-en-gb-1bfe-2.php
http://amik.closa.com/unx/video-Jablonec-Dynamo-ceske-Budejovice-v-en-gb-kbo-.php
http://amik.closa.com/unx/videos-Jablonec-Dynamo-ceske-Budejovice-v-en-gb-gvl-.php
https://cartaodosus.info/video.php?video=v-ideos-Gasogi-United-Rwanda-Police-FC-v-en-gb-1sgi-16.php
https://cartaodosus.info/video.php?video=Video-AS-Ain-M'lila-JSM-Skikda-v-en-gb-1pva-16.php
https://cartaodosus.info/video.php?video=videos-AS-Ain-M'lila-JSM-Skikda-v-en-gb-1xxc-18.php
http://amik.closa.com/unx/v-ideos-jablonec-v-dynamo-ceske-v-cs-cs-1kyz-9.php
http://mid.actiup.com/ktb/videos-Al-Fehaheel-Al-Tadamon-SC-v-en-gb-1rlt-8.php
https://cartaodosus.info/video.php?video=v-ideos-AS-Ain-M'lila-JSM-Skikda-v-en-gb-1wih-2.php
https://test.activesilicon.com/xrp/Video-Birkirkara-Gzira-United-v-en-gb-1auo-10.php
http://great.gruposio.es/pkm/Video-Birkirkara-Gzira-United-v-en-gb-1abg-.php
http://amik.closa.com/unx/Video-jablonec-v-dynamo-ceske-v-cs-cs-1ejr-10.php
https://cartaodosus.info/video.php?video=videos-MTK-Budapest-Paksi-v-en-gb-1htn-2.php
http://amik.closa.com/unx/videos-jablonec-v-dynamo-ceske-v-cs-cs-1ecz-3.php
http://mileno.provecracing.com/hxm/v-ideos-Knockbreda-Loughgall-v-en-gb-1hzt-11.php
https://cartaodosus.info/video.php?video=Video-MTK-Budapest-Paksi-v-en-gb-1dtn-17.php
https://cartaodosus.info/video.php?video=video-MTK-Budapest-Paksi-v-en-gb-1kyl-17.php
http://amik.closa.com/unx/video-Pribram-Karvina-v-en-gb-ojg-.php
https://cartaodosus.info/video.php?video=v-ideos-mtk-budapest-v-paksi-v-hu-hu-1hzj-16.php
http://amik.closa.com/unx/Video-Pribram-Karvina-v-en-gb-akq-.php
http://amik.closa.com/unx/video-Pribram-Karvina-v-en-gb-lvl-.php
https://cartaodosus.info/video.php?video=v-ideos-mtk-budapest-v-paksi-v-hu-hu-1gbd-5.php

It may give a clue that lexical scoping is about determining scope based on body of text itself. The code as you read it. It you do not have to consider how the code is executed or how the state of your environment changes over time.

That is why we tend to prefer lexical scoping. You can simply examine the code to figure out where the value of a variable comes from. So other possible ways to help you remember lexical scoping is that we could also call it:

  • Textual scope. The text as it stands decides the value of a variable.
  • Static scope. The compiler should be able to figure out how the variable is assigned a value. No need to run the program.

Enough Musings! Give Me a Code Example!

Okay, you want to cut to the chase. So let us build up an example. I like science so let us do some Newton motion equations. This is the the velocity v at time t if initial velocity at time t=0 was v0 :

v = a*t + v0

Usually in these cases we want to express this as a function of t and we don’t want to pass the acceleration a and initial velocity v0 in as arguments. Hence we write code like this:

a  = 4
v0 = 10
velocity(t) = a*t + v0

This is Julia code, so we could use the Julia command line (REPL) and use this function like this:

julia> velocity(1)
14
julia> velocity(2)
18

And whenever you want you could change the parameters a and v0 use to alter this calculation:

julia> v0 = 100
100
julia> velocity(1)
104
julia> v0 = 0
0
julia> velocity(1)
4

But what if we wanted to reuse this velocity function to create a velocity function for say the moon or something and everything worked different there. Maybe somehow we got better start velocity.

function moon_velocity(t)
a = 10
v0 = 100
return velocity(t)
end

Let us try this in the Julia command line (REPL):

julia> moon_velocity(1)
4

Nope, that doesn’t work so well. Why? Because Julia does not use dynamic scoping. The velocity function is not going to look for the acceleration a and initial velocity v0 in the scope it gets called from. It looks for these parameters based on where they where defined in code relative to the definition of the velocity function. In other words it is textual. You look at the code around.

Yet this kind of functionality would be kind of useful, which is perhaps why people initially thought dynamic scoping was a good idea. So how do we typically solve this problem in a language with lexical scoping? We wrap our velocity function inside another function so we can create a new lexical scope over and over again capturing different varibles:

function make_velocity(a, v0)
return function(t)
a*t + v0
end
end

Now we can make velocity and moon_velocity functions like this:

velocity = make_velocity(4, 10)moon_velocity = make_velocity(10, 100)

When Do You Want Dynamic Scope?

So do we need dynamic scope at all? Turns out there are a number of cases where it is useful. E.g. when you launch a program in a Unix system e.g. from the terminal you basically got dynamic scope.

The new process inherits the environment from the parent process (the terminal), with things such as environment variables. In this case that is desirable behavior. You don’t want environment variables for a process to be bound to wherever the program code was written (lexical scope).

You are not going to be looking at code in that context anyway. In this case the runtime environment is more natural to think of as the starting-point.

Dynamic Scope for Loggers

Another example where we would want dynamic scope is for loggers. In many logging frameworks the logger is quite static:

logger.warning("something bad happened, fix it!")

The module has some variable logger which is used as the logger. That means you have fixed for the whole module, class or whatever granularity one operates with, what the logger should be.

That is inflexible. In this case we want dynamic scope. We want the runtime environment, the code calling another function to decide what logger that specific function should use, right there and then. In another context you may want it to use another logger.

This is a bit of a contrived example so bear with me. It is supposed to illustrate that you potentially have a deep call stack where the same function can be called in different contexts:

function inner_dummy(x)
@info "my log message" x
end
function outer_dummy(x)
inner_dummy(x)
with_logger(Logging.global_logger()) do
inner_dummy(x+10)
end
end

In this case we got inner_dummy which is called twice from outer_dummy. What I want to show here is that the function is not permanently bound to one specific logger. The dynamic environment decides what the logger is.

To demonstrate this we must make some alternative loggers to use:

io = open("log.txt", "w+")
logger = SimpleLogger(io)

Now we can call outer_dummy using this logger as the context:

with_logger(logger) do
@info "hello world"
outer_dummy(3)
end

When done we close the iostream io , so we can look at the content of the log file log.txt which we created.

close(io)

If we run this in the terminal we get the following log message in the terminal window:

┌ Info: my log message
└ x = 13

However in the log.txt file we get:

┌ Info: hello world
└ @ Main REPL[9]:2
┌ Info: my log message
│ x = 3
└ @ Main REPL[2]:2

Conclusion, You Need Both

So while at the programming language level we typically prefer lexical scoping, dynamic scoping still is useful in various contexts. You are not always in a situation where reading the source code to determine how a variable is bound can be determined. You cannot do that with processes in the Unix shell e.g.

And the predictable nature of binding a variable in the scope, that you desire for most things in your source code is not desirable for a logger. In this case you want to be able to switch around the loggers. You don’t want the source code to predetermine the logger you use. The caller should decide.

Hopefully with some of these practical examples, motivating the use of each type of scope it will be easier to remember until next time, so you don’t have to look up the definition every time like me 😉

Cambridge medicine grad, striving to improve healthcare through technology and education.