[BangPypers] Does Python have lexical scoping?

Abhishek L abhishek.lekshmanan at gmail.com
Mon Nov 10 07:17:20 CET 2014


Senthil Kumaran writes:

> On Sun, Nov 9, 2014 at 1:14 AM, Noufal Ibrahim KV <noufal at nibrahim.net.in>
> wrote:
>
>> How is lexical scoping with a mutable environment different from dynamic
>> scoping?
>>
>
> I think you should post this in python-dev and you might get answers with
> rigorous definitions.
>
> Here is my short snippet which shows a behavior which does not indicate a
> dynamic binding nature.
>
>
> # example.py
> x = 10
> y = lambda: x
>
> def f():
>     x = 20  # This is not rebinding. It is creating a new local variable by
> name x
>             # But we are referring to x in y function call, so for the
> definition of dynamic binding (?)
>             # should y() see x defined in the local scope instead of the
> previously assigned value.
>     print(y())
>     return y()
>
> x = 30  # This is rebinding in the same scope.
> print(f())
>
> $ python example.py
> 30
> 30

Just for understanding, trying the same snippet in emacs lisp which has
dynamic binding will reveal the value of `x' as 20, as expected in
dynamic binding as we change the value of x inside the function.

(setq x 10)
(defun y () x)

(defun f () (setq x 20) (print (y)) (y))
(print (f)) ; 20 20 


-- 
Abhishek


More information about the BangPypers mailing list