In Python, a function has access to all variables in-scope at the time of its creation. What is this feature called?
JavaScript has this same behavior, and we say that functions are lexical-scoped in it. Will the same apply to Python?
In Python, a function has access to all variables in-scope at the time of its creation. What is this feature called?
JavaScript has this same behavior, and we say that functions are lexical-scoped in it. Will the same apply to Python?
In Python, a function has access to all variables in-scope at the time of its creation. What is this feature called?
A Python function actually has access to all the variable in the scope of its creation, even those defined after the function is closed.
The property that a function can access content from its definition environment is called closing over, that function defines (or colloquially is) a closure.
JavaScript has this same behavior, and we say that functions are lexical-scoped in it. Will the same apply to Python?
Lexical scoping does apply to function, but it mostly has to do with the chain taken to resolve names: lexical scoping means the names are resolved at the point of definition, dynamic scoping is the other big one and means the names are resolved as the point of use.
Lexical or dynamic scoping applies to all scopes, so in most languages it will also (or only) apply to blocks (e.g. Python only has function-level scoping, C only has block-level scoping, Go has both).
Yeah, python has lexical scoping, but environments are mutable. Such as if x=1
and f()
returns x
but before calling if x is 10 then return value is 10.
In Python, just as in SML, or modern Lisp, the body of a function is evaluated in the environment where it was defined. So, all three languages are lexically scoped.
But In Python, environments are mutable. That is, you can assign a new value to an existing variable, and that mutates the environment the variable is part of. Any functions defined within that environment will be evaluated in that environment—which means they will see the new value of the variable.
From: Does Python scoping rule fits the definition of lexical scoping?