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:
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:
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!