1. Concept Overview
Function scope and lifetime determine:
Where variables are accessible
How long variables exist in memory
Python follows the LEGB Rule for scope resolution:
This defines how Python resolves variable names at runtime.
Variables defined inside a function belong to the local scope.
def calculate():
result = 50
print(result)
calculate()
# print(result) # NameError
Local variables exist only during function execution.
3. Global Scope
Variables defined outside functions are global.
Accessible throughout the module unless overridden.
4. Enclosing Scope (Nested Functions)
Inner functions can access variables from their enclosing scope.
5. Built-in Scope
Python reserves predefined identifiers:
Avoid overriding built-ins.
6. LEGB Resolution Demonstration
Variable resolution order:
Local ➝ Enclosing ➝ Global ➝ Built-in.
7. Variable Lifetime
Lifecycle of variables:
Created when function is called
Destroyed after execution completes
temp is deallocated after function exit.
8. Using global Keyword
Allows modifying global variables inside functions.
9. Using nonlocal Keyword
Modifies variables in enclosing (non-global) scope.
10. Scope Isolation Examples
Python does not have block scope; it has function scope.
Scope Types Summary
Variable Lifetime Phases
Destroyed (garbage collected)
Common Pitfalls
Forgetting global when modifying globals
Shadowing outer scope variables
Overlapping variable names
Accidental redefinition of built-ins
Real-World Enterprise Example
Used in:
Configuration propagation
Overuse of globals increases coupling
Deeply nested scopes reduce readability
Memory not freed if references persist
Minimize global variable usage
Use function parameters instead of globals
Prefer nonlocal for closures
Use scoped variables for clarity
Enterprise Importance
Understanding scope and lifetime ensures:
Predictable variable behavior
Maintainable architecture
Critical for:
AI pipeline orchestration
Last updated