Variable Scope and Lifetime in Python
In Python, the scope of a variable refers to the region of the program where the variable is accessible, while the lifetime of a variable is the duration for which the variable exists in memory. Understanding these concepts is essential for managing variable accessibility and memory usage in your programs.
Key Points on Variable Scope:
- Local Scope: Variables defined within a function are local to that function and cannot be accessed outside of it.
- Global Scope: Variables defined outside of any function have a global scope and can be accessed throughout the entire program.
- Enclosing Scope: In nested functions, the inner function can access variables defined in the outer function's scope.
- Built-in Scope: Python has a built-in scope for variables that are always available, such as functions like
print()
andlen()
. - Shadowing: A local variable can shadow a global variable with the same name, meaning the local variable takes precedence within its scope.
Example of Variable Scope:
Code Example
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print("Inside function:", y)
print("Global variable inside function:", x)
my_function()
print("Global variable outside function:", x)
# print(y) # Uncommenting this line will raise a NameError
Output
Inside function: 5
Global variable inside function: 10
Global variable outside function: 10
Global variable inside function: 10
Global variable outside function: 10
Variable Lifetime:
- Local Variable Lifetime: Local variables are created when the function is called and destroyed when the function exits.
- Global Variable Lifetime: Global variables exist as long as the program runs and are destroyed when the program terminates.
- Temporary Objects: Variables created within a function may reference temporary objects that are also destroyed once the function ends, impacting memory usage.
Understanding variable scope and lifetime helps developers write cleaner code, avoid unintended behavior, and manage memory efficiently.