1. What is Scope in Python
Scope defines the region of a program where a variable is accessible.
Python follows the LEGB Rule:
x = 10 # Global
def show():
y = 5 # Local
print(x, y)
show()
Determines where Python searches for a variable during execution.
2. Local Scope
Variables declared inside a function belong to local scope.
def calculate():
total = 100
print(total)
calculate()
# print(total) # Error: total not defined
Local variables exist only within the function block.
3. Global Scope
Variables declared outside all functions exist globally.
Accessible throughout the entire module.
4. Enclosing Scope (Nested Functions)
Variables from outer functions are available to inner functions.
5. Built-in Scope
Python provides built-in reserved names.
Examples:
len, sum, range, type, print
Avoid overriding built-ins.
6. LEGB Variable Resolution Example
Search order:
Local → Enclosing → Global → Built-in
7. Lifetime of Variables
Lifetime is the duration for which a variable exists in memory.
temp lives only while the function is executing.
8. Using global Keyword
Allows modifying global variables inside functions.
9. Using nonlocal Keyword
Modifies variables in the enclosing scope.
10. Scope Isolation Example
Python does not use block scope; it uses function scope.
Scope Types Summary
Outer function of nested functions
Variable Lifetime Stages
Garbage collected when out of scope
Common Scope Pitfalls
Modifying globals without global
Forgetting nonlocal in closures
Misunderstanding nested scopes
Minimize use of global variables
Prefer function parameters
Use meaningful variable names
Encapsulate logic in functions/classes
Enterprise Impact
Understanding scope and lifetime ensures:
Predictable variable behavior
Optimized resource utilization
Critical for:
Last updated