Scope: Where Variables Live
Understanding how Python finds and resolves variable names is essential for writing correct and bug-free code. The LEGB rule is at the heart of this process. LEGB stands for Local, Enclosing, Global, and Built-in, and it describes the order in which Python searches for a variable name when it is referenced in code.
- Local: The innermost scope, usually within a function or method, where variables are defined by assignment;
- Enclosing: Any enclosing function scopes, if the function is nested inside another function;
- Global: The top-level scope of the module or script in which code is running;
- Built-in: The special scope containing Pythonβs built-in names, such as
lenorrange.
When you use a variable name, Python first looks in the local scope. If it is not found, it checks any enclosing scopes, then the global scope, and finally the built-in scope. This process ensures that variable names are resolved in a predictable way, even when functions are nested.
123456789101112131415# Illustrating LEGB rule with nested functions def outer(): x = "enclosing" def inner(): x = "local" print("Inner:", x) # Local scope inner() print("Outer:", x) # Enclosing scope x = "global" outer() print("Global:", x) # Global scope print("Built-in:", len([1, 2, 3])) # Built-in scope
Scope not only determines where you can access a variable, but also how long it lives and when it is destroyed. Variables defined inside a function exist only while the function runs; after that, they are gone. Variables in the global scope persist for the lifetime of the program. One common pitfall is accidentally modifying a variable in an unexpected scope, which can lead to bugs that are hard to trace.
If you assign to a variable inside a function, Python treats it as a local variable unless you explicitly declare it as global or nonlocal. This can cause confusion when a variable with the same name exists in an outer scope.
For instance, consider the following example where modifying a variable inside a nested function does not affect the variable in the enclosing scope unless you use the nonlocal or global keyword.
1234567891011# Modifying variables in different scopes def counter(): count = 0 def increment(): count = count + 1 # UnboundLocalError: count referenced before assignment return count return increment # This will raise an error if you call counter() and then try to increment, # because 'count' is treated as a new local variable in increment(), not the enclosing one.
1. What does the LEGB rule stand for?
2. How does Python resolve a variable name inside a nested function?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain how to fix the UnboundLocalError in the counter example?
What is the difference between the global and nonlocal keywords in Python?
Can you give more examples of how scope affects variable access in nested functions?
Awesome!
Completion rate improved to 8.33
Scope: Where Variables Live
Swipe to show menu
Understanding how Python finds and resolves variable names is essential for writing correct and bug-free code. The LEGB rule is at the heart of this process. LEGB stands for Local, Enclosing, Global, and Built-in, and it describes the order in which Python searches for a variable name when it is referenced in code.
- Local: The innermost scope, usually within a function or method, where variables are defined by assignment;
- Enclosing: Any enclosing function scopes, if the function is nested inside another function;
- Global: The top-level scope of the module or script in which code is running;
- Built-in: The special scope containing Pythonβs built-in names, such as
lenorrange.
When you use a variable name, Python first looks in the local scope. If it is not found, it checks any enclosing scopes, then the global scope, and finally the built-in scope. This process ensures that variable names are resolved in a predictable way, even when functions are nested.
123456789101112131415# Illustrating LEGB rule with nested functions def outer(): x = "enclosing" def inner(): x = "local" print("Inner:", x) # Local scope inner() print("Outer:", x) # Enclosing scope x = "global" outer() print("Global:", x) # Global scope print("Built-in:", len([1, 2, 3])) # Built-in scope
Scope not only determines where you can access a variable, but also how long it lives and when it is destroyed. Variables defined inside a function exist only while the function runs; after that, they are gone. Variables in the global scope persist for the lifetime of the program. One common pitfall is accidentally modifying a variable in an unexpected scope, which can lead to bugs that are hard to trace.
If you assign to a variable inside a function, Python treats it as a local variable unless you explicitly declare it as global or nonlocal. This can cause confusion when a variable with the same name exists in an outer scope.
For instance, consider the following example where modifying a variable inside a nested function does not affect the variable in the enclosing scope unless you use the nonlocal or global keyword.
1234567891011# Modifying variables in different scopes def counter(): count = 0 def increment(): count = count + 1 # UnboundLocalError: count referenced before assignment return count return increment # This will raise an error if you call counter() and then try to increment, # because 'count' is treated as a new local variable in increment(), not the enclosing one.
1. What does the LEGB rule stand for?
2. How does Python resolve a variable name inside a nested function?
Thanks for your feedback!