Press ESC to close

What is Scope and Lifetime of a Variable in Python

In Python, the scope and lifetime of a variable are important concepts that define where a variable can be accessed and how long it exists in memory.

1. Scope of a Variable

Scope refers to the region of the code where a variable is recognized and can be accessed. There are four levels of scope in Python:

  • Local Scope: Variables defined inside a function have a local scope. They can only be accessed within that function.
def my_function():
    local_var = 10
    print(local_var)  # Accessible here

my_function()
# print(local_var)  # This would raise an error because local_var is not accessible here

Enclosing (Nonlocal) Scope: This is specific to nested functions. Variables defined in an outer function are accessible in the inner function, but they are not global.

def outer_function():
    enclosing_var = "I'm an enclosing variable"
    
    def inner_function():
        print(enclosing_var)  # Accessible here because of enclosing scope
    
    inner_function()

outer_function()

Global Scope: Variables defined at the top level of a script or module, or with the global keyword, are accessible throughout the module and across functions (unless shadowed by local variables).

global_var = "I'm global"

def my_function():
    print(global_var)  # Accessible here because it's in the global scope

my_function()
print(global_var)  # Accessible here as well

Built-in Scope: This is the scope containing all the built-in functions and exceptions in Python. For example, functions like print(), len(), and range() are in the built-in scope.

print(len("Hello, World!"))  # len() is in the built-in scope

2. Lifetime of a Variable

Lifetime refers to the duration for which a variable exists in memory.Local Variables: The lifetime of a local variable is limited to the function’s execution. Once the function finishes executing, the local variables are destroyed and the memory is freed.

def my_function():
    local_var = 10  # Created when function is called
    print(local_var)

my_function()  # After this call, local_var is destroyed

Global Variables: Global variables have a lifetime that lasts as long as the program is running. They are created when the program starts and destroyed when the program ends or when they are explicitly deleted using del.

global_var = 100  # Created when program starts

def my_function():
    print(global_var)

my_function()
# global_var exists until the program ends or it's deleted explicitly
  • Nonlocal Variables: In nested functions, variables in the enclosing scope (nonlocal) have a lifetime tied to the lifetime of the outer function.

3. Shadowing and Variable Resolution

A variable in a higher scope can be “shadowed” by a variable with the same name in a lower scope (e.g., a local variable with the same name as a global variable). In such cases, the innermost scope takes precedence.

var = "I'm global"

def my_function():
    var = "I'm local"  # This shadows the global var inside the function
    print(var)  # Prints "I'm local"

my_function()
print(var)  # Prints "I'm global" because the global variable is not affected

Summary

  • Scope: Determines where a variable can be accessed (local, enclosing, global, built-in).
  • Lifetime: Determines how long a variable exists in memory (local variables exist during function execution, global variables exist throughout the program).

Understanding scope and lifetime helps in managing variable access and memory usage efficiently in Python programs.

Leave a Reply

Your email address will not be published. Required fields are marked *