![How Does Python's LEGB Rule Determine Variable Scope?](https://img.php.cn/upload/article/000/000/000/173491059395202.jpg)
Python's LEGB Rule: Demystifying Scoping Rules
Python's scoping rules, often a source of confusion, can be readily apprehended through the LEGB rule.
LEGB Rule
The LEGB rule provides a clear algorithm for determining the availability of variables within a given scope:
-
L (Local): Variables defined within a function or lambda expression.
-
E (Enclosing-function): Variables defined in enclosing functions, from inner to outer.
-
G (Global): Variables defined at the module level or declared global within a function.
-
B (Built-in): Pre-assigned variables from Python's built-in names module.
Example
Consider the following code:
class Foo:
def spam():
for var in []:
x()
Using the LEGB rule, we can determine the scope of the variable x:
-
L: None. x is not defined locally within the spam function.
-
E: None. The spam function is not nested within another function.
-
G: Yes. If x is defined at the module level, it will be available within the spam function.
-
B: Yes. If x is a built-in variable (e.g., a Python function), it will be accessible.
In this example, x would be found if it were defined at the module level or is a Python built-in.
The above is the detailed content of How Does Python's LEGB Rule Determine Variable Scope?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn