Python Scope
In Python, "scope" refers to the region or context in which a variable is defined and can be accessed. Python has different levels of scope, including global scope and local scope, and the scope of a variable determines where it can be used or accessed in your code. Understanding scope is crucial for writing clean, maintainable, and bug-free Python programs. Here, I'll explain in detail about Python scope with sample code.
1. Local Scope:
Variables defined within a function have local scope. They are only accessible within that function.
A new local scope is created every time a function is called, and it is destroyed when the function exits.
def my_function():
local_variable = 42
print(local_variable)
my_function() # Calls the function
print(local_variable) # Raises a NameError because local_variable is not defined here
2. Enclosing (Non-Local) Scope:
In nested functions, variables can be in an "enclosing" scope, also known as a "non-local" scope.
Variables in the enclosing scope are not global but are accessible within the nested functions.
def outer_function():
outer_variable = 10
def inner_function():
print(outer_variable) # Accesses the outer_variable from the enclosing scope
inner_function()
outer_function()
3. Global Scope:
Variables defined outside of any function have global scope. They can be accessed from any part of the program.
global_variable = 100
def my_function():
print(global_variable) # Accesses the global_variable
my_function()
4. Built-in Scope:
Python has a built-in scope that contains functions and objects provided by Python itself.
You can access built-in functions and objects like print(), len(), str, and int without importing them.
print(len("Hello, World!")) # Accesses the len() function from the built-in scope
5. Modifying Variables in an Enclosing Scope:
To modify a variable in an enclosing scope from within a nested function, you can use the nonlocal keyword.
def outer_function():
outer_variable = 10
def inner_function():
nonlocal outer_variable # Use nonlocal to modify outer_variable
outer_variable += 5
inner_function()
print(outer_variable) # Prints 15
outer_function()
6. Global Variables:
You can declare a variable as global inside a function using the global keyword.
This allows you to modify the global variable within the function.
global_variable = 100
def modify_global():
global global_variable # Declare global_variable as global
global_variable += 10
modify_global()
print(global_variable) # Prints 110
Scope determines where a variable is visible and accessible. Python follows the LEGB (Local, Enclosing, Global, Built-in) rule for variable name resolution, which means it first looks for a variable in the local scope, then in any enclosing scopes, then in the global scope, and finally in the built-in scope.
No comments:
Post a Comment