Python Scope and Lifetime

1. What is Scope in Python

Scope defines the region of a program where a variable is accessible.

Python follows the LEGB Rule:

  • Local

  • Enclosing

  • Global

  • Built-in

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

Scope Type
Description

Local

Inside function

Enclosing

Outer function of nested functions

Global

Top-level of module

Built-in

Python reserved names


Variable Lifetime Stages

Phase
Description

Creation

Variable defined

Active

Accessible and in memory

Termination

Garbage collected when out of scope


Common Scope Pitfalls

  • Modifying globals without global

  • Shadowing built-in names

  • Forgetting nonlocal in closures

  • Misunderstanding nested scopes


Best Practices

  • Minimize use of global variables

  • Prefer function parameters

  • Avoid name collisions

  • Use meaningful variable names

  • Encapsulate logic in functions/classes


Enterprise Impact

Understanding scope and lifetime ensures:

  • Memory efficiency

  • Predictable variable behavior

  • Clean modular design

  • Avoidance of subtle bugs

  • Optimized resource utilization

Critical for:

  • Multithreaded systems

  • Large-scale applications

  • AI model pipelines

  • Distributed services


Last updated