According to my programming language class, in a language that uses lexical scoping
The body of a function is evaluated in the environment where the function is defined, not the environment where the function is called.
For example, SML follows this behavior:
val x = 1
fun myfun () =
x
val x = 10
val res = myfun() (* res is 1 since x = 1 when myfun is defined *)
On the other hand, Python does not follow this behavior:
x = 1
def myfun():
return x
x = 10
myfun() # 10 since x = 10 when myfun is called
So why is Python described as using lexical scoping?
JavaScript and other languages such as the C family and Python use lexical scope , also called static scope , which means that scope nests according to where functions and variables are declared.
Python uses lexical scoping, there is no dynamic scoping.
The Python scope concept is generally presented using a rule known as the LEGB rule. The letters in the acronym LEGB stand for Local, Enclosing, Global, and Built-in scopes. This summarizes not only the Python scope levels but also the sequence of steps that Python follows when resolving names in a program.
Explanation: The fundamental rule of lexical scoping is that the JavaScript functions are executed using the scope chain that was in effect when they were defined.
Your Python myfun
is using the x
variable from the environment where it was defined, but that x
variable now holds a new value. Lexical scoping means functions remember variables from where they were defined, but it doesn't mean they have to take a snapshot of the values of those variables at the time of function definition.
Your Standard ML code has two x
variables. myfun
is using the first variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With