[BangPypers] Does Python have lexical scoping?

Abhishek L abhishek.lekshmanan at gmail.com
Sun Nov 9 09:20:40 CET 2014


I'll try to explain a bit, have to admit though, even my understanding
is not all that clear, and all is open for further discussion.

Noufal Ibrahim KV writes:

> 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.
>
Here, technically ML's val bindings are actually immutable. When you
actually do a val x = 10; you're creating a new binding for x *shadowing*
the previous binding. Something like

fun f y = x + y;

creates a closure with f, and the free variable x.The closure locks
the function with the environment the function was defined in, locking x
to 2, as variables are always looked up in the dynamic environment they
are defined in before they are called, x is bound to 2. Also ML will not
allow you to define a function with x not previously defined, (ie no
forward lookups)

> With python, it's different. The claim is that it has lexical scoping
> but.
>
>      x = 2
>      def f(y): return x + y
>
>      x = 10
>      f(3)
>
> The answer is, distressingly, 13. The explanation was that although
> Python has lexical scoping, that closure "close over variables rather
> than values".

Here x was a mutable variable, doing a similiar ML construct, ie

     val x = ref 2
     fun f y = !x + 2

     f 10 ; evals to 12
     x := 10
     f 10 ; evals to 20

So this becomes a problem of closures over mutable variables? ie every
closure looks up the value of same variable, x which gets mutated
around. WDYT?

PS I'm not sure whether this mail is going to hit twice in the list,
had replied some 30 mins ago, but the mail still failed to appear in the list
--
Regards
Abhishek


More information about the BangPypers mailing list