Junior
258
How does the LEGB rule work in Python?
Answer from AI
sobes.tech AI
The LEGB rule defines the order in which Python searches for names (variables, functions, classes, etc.) in different scopes. The acronym stands for:
- Local (Local scope): Inside the current function.
- Enclosing (Enclosing scope): The enclosing function (if any), in which the current function is defined (for nested functions).
- Global (Global scope): At the module level.
- Built-in (Built-in scope): Python's built-in names (e.g.,
print,len,range).
Python searches for a name starting from the local scope. If not found, it moves to the enclosing scope, then to the global scope, and finally to the built-in scope. Once the name is found, the search stops.