python

Scope and lifetime of variables


Understanding the scope and lifetime of variables is crucial for effective programming in Python. In Python, the lifetime of a variable is determined by its scope, which can be global, local, or nonlocal.

 

 

 

1. Global Variables(scope)

 

Definition:

  • Global variables are defined outside any function or block.
  • They can be accessed from any part of the code, including inside functions and classes.

 

Lifetime:

  • Global variables exist for the lifetime of the program.
  • They are created when the program starts and destroyed when the program terminates.

Example:

global_var = "I am a global variable"
def my_function():
   print(global_var)
my_function()  # Output: I am a global variable
 

 

2. Local Variables(scope)

 

Definition:

  • Local variables are defined within a function.
  • They can only be accessed within that function.

 

Lifetime:

  • Local variables exist only during the execution of the function.
  • They are created when the function is called and destroyed when the function exits.

Example:

def my_function():
   local_var = "I am a local variable"
   print(local_var)
my_function()  # Output: I am a local variable
# print(local_var)  # This would raise an error as local_var is not defined outside the function
 

 

3.Enclosing Scope (Nonlocal Scope)

Enclosing scope refers to the scope of variables in enclosing functions, applicable in nested functions. These variables can be accessed but not modified in the inner functions unless declared with the nonlocal keyword.

 

Example:

def outer_function():
   enclosing_var = "I am an enclosing variable"
   
   def inner_function():
       nonlocal enclosing_var
       enclosing_var = "I have been modified"
       print(enclosing_var)
   
   inner_function()
   print(enclosing_var)
outer_function()
# Output:
# I have been modified
# I have been modified
 

 

4.Built-in Scope

The built-in scope is a special scope that contains Python's built-in functions and exceptions. These are always available and can be accessed from any part of the code.

 

Example:

print(len("Hello"))  # Output: 5
 

 


python