Scope in Python
Scope in Python
Scope in Python refers to the region of the program where a particular variable is accessible. In Python, variables can be classified into different types based on their scope. Understanding scope is important because it helps determine where a variable can be accessed and modified.
There are four types of scope in Python:
Local Scope
Enclosing Scope
Global Scope
Built-in Scope
Let's break down each of these scopes with examples.
1. Local Scope
The local scope refers to the area within a function where variables are created and accessed. These variables are only accessible within that function.
Example of Local Scope:
def my_function(): x = 10 # x is local to my_function print(x) # Accessible heremy_function()# Outside the function, x is not accessible# print(x) # This would result in a NameErrorHere, x is defined inside my_function, so it is only available within that function. Trying to access x outside the function will lead to a NameError.
2. Enclosing Scope
The enclosing scope refers to the scope of a function that contains another function. In this case, variables defined in the outer function can be accessed by the inner function but not the other way around.
Example of Enclosing Scope:
def outer_function(): x = 20 # x is in the enclosing scope def inner_function(): print(x) # Can access x from the enclosing scope inner_function()outer_function()In this example, x is defined in the outer function (outer_function), and the inner function (inner_function) can access x because it is in the enclosing scope. However, outer_function cannot access variables defined inside inner_function.
3. Global Scope
The global scope refers to variables that are defined at the top level of the script or module, outside of any function or class. These variables are accessible throughout the script.
Example of Global Scope:
x = 30 # x is in the global scopedef my_function(): print(x) # Can access x because it is in the global scopemy_function()print(x) # x is accessible globallyHere, x is a global variable because it is defined outside of any function. Both the function my_function and the global scope can access x.
4. Built-in Scope
The built-in scope refers to variables and functions that are always available in Python. These are the standard functions and exceptions that Python provides. For example, print(), len(), and int() are built-in functions.
Example of Built-in Scope:
# Using a built-in functionprint("Hello, World!") # print is built-in# Accessing a built-in exceptiontry: x = 1 / 0except ZeroDivisionError: print("Cannot divide by zero")print and ZeroDivisionError are part of Python's built-in scope, meaning they are always available without needing to import them.
LEGB Rule
Python uses the LEGB rule (Local, Enclosing, Global, Built-in) to resolve variable names. When a variable is referenced, Python will search for it in the following order:
Local: The innermost scope (inside the current function).
Enclosing: Any enclosing functions (non-local functions, such as outer functions).
Global: The scope of the module or script.
Built-in: The built-in scope, which contains Python's built-in functions and exceptions.
Example: LEGB Rule
x = "Global"def outer(): x = "Enclosing" def inner(): x = "Local" print(x) # Will print "Local" inner()outer()print(x) # Will print "Global"In this case:
Inside
inner(), Python first looks forxin the local scope (insideinner()), then the enclosing scope (insideouter()), then the global scope, and finally, it checks the built-in scope if it hasn't found it earlier.
Global and Local Variables
You can access and modify global variables inside a function using the global keyword. However, if you don't use global, Python will treat the variable inside the function as a local variable.
Example: Modifying Global Variable
x = 10 # Global variabledef modify_global(): global x x = 20 # Modifies the global variable xmodify_global()print(x) # x will be 20, as it was modified globallyWithout the global keyword, Python would create a local variable named x inside the function, and the global variable would remain unchanged.
Nonlocal Keyword
The nonlocal keyword is used to work with variables inside a nested function, where the variable is not local to the function, but not global either.
Example: Nonlocal Variable
def outer(): x = 10 # Enclosing variable def inner(): nonlocal x x = 20 # Modifies the enclosing variable x inner() print(x) # x will be 20, as it was modified inside inner()outer()Here, nonlocal allows the inner() function to modify the x variable from the enclosing scope (outer()), instead of creating a new local variable.
Summary
Local Scope: Variables defined inside a function. Accessible only within that function.
Enclosing Scope: The scope of functions that contain other functions. Accessible from inner functions.
Global Scope: Variables defined at the top level of a script or module. Accessible anywhere in the script.
Built-in Scope: Predefined variables and functions that are always available in Python.
The LEGB rule helps Python determine where to look for variables when they're accessed. The global and nonlocal keywords allow you to modify variables in global and enclosing scopes, respectively.