[BangPypers] Does Python have lexical scoping?

Noufal Ibrahim KV noufal at nibrahim.net.in
Sun Nov 9 06:08:31 CET 2014

Okay, I've been struggling through the proglang course on coursera and
this thing came up

   val x = 2;
   fun f y = x + y;

The second line creates a function that adds `x` to it's argument. Since
ML is statically scoped, this is really a function that adds 2 to its
argument.  Even if I later create a new binding for x later like so

   val x = 10;
   f (3);

I will still get back 5 (i.e. 2 + 3) instead of 13 (10 + 3). This makes
sense to me as an example of lexical scoping. The bindings are at the
time of definition rather than invocation.

With python, it's different. The claim is that it has lexical scoping

     x = 2
     def f(y): return x + y
     x = 10 

The answer is, distressingly, 13. The explanation was that although
Python has lexical scoping, that closure "close over variables rather
than values". Meaning that the variables (and not their values) at
definition time are stored in the closure. This is how elisp does it
which claims to be, by default, dynamically scoped.

(setq m 5)
(defun test (x)
  (+ x m))

(test 3) ; -> 8
(setq m 15)
(test 3) ; -> 18

So, my question is, how different is this from dynamic scoping (like in
elisp) where the values are actually picked up from the execution
(rather than definition) environment. This business of "closes over
variables rather than values" sounds like a cop out.



More information about the BangPypers mailing list