Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python scoping rule fits the definition of lexical scoping?

Tags:

python

scope

sml

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?

like image 917
Heisenberg Avatar asked Jul 31 '18 01:07

Heisenberg


People also ask

Does Python have 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.

Does Python use lexical or dynamic scoping?

Python uses lexical scoping, there is no dynamic scoping.

What are the scoping rules for Python?

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.

What is the primary rule of the lexical scoping?

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.


1 Answers

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.

like image 183
user2357112 supports Monica Avatar answered Sep 22 '22 12:09

user2357112 supports Monica