Python Scope of Variables
Scope of Variables in Python
The scope of a variable refers to the context in which a variable is defined and accessible. In Python, the scope determines the visibility and lifetime of a variable in your code. Understanding variable scope is essential for managing the visibility of variables in functions, classes, and modules.
There are four main types of variable scope in Python:
- Local Scope
- Enclosing Scope (Nonlocal)
- Global Scope
- Built-in Scope
Let's explore each type in detail.
1. Local Scope
- Definition: A variable defined within a function or a block of code has a local scope. It can only be accessed within that function or block.
- Lifetime: The variable exists only as long as the function is executing.
Example of Local Scope
In this example, local_var
is only accessible within my_function()
. Attempting to access it outside the function raises a NameError
.
2. Enclosing Scope (Nonlocal)
- Definition: This scope applies to variables defined in a nested function. A variable in an outer (enclosing) function can be accessed from an inner (nested) function but not modified unless specified with the
nonlocal
keyword. - Lifetime: The variable exists as long as the outer function is executing.
Example of Enclosing Scope
In this example, outer_var
is defined in outer_function()
and is accessible inside inner_function()
, demonstrating the concept of enclosing scope.
Modifying Variables in Enclosing Scope
To modify a variable from the enclosing scope within a nested function, you can use the nonlocal
keyword:
3. Global Scope
- Definition: A variable defined at the top level of a script or module has a global scope. It can be accessed from any function within the same module.
- Lifetime: The variable exists as long as the program runs.
Example of Global Scope
If you want to modify a global variable within a function, you must use the global
keyword:
4. Built-in Scope
- Definition: This scope contains built-in names that are always available in Python, such as functions like
print()
,len()
, etc. - Lifetime: These names are available as long as the Python interpreter is running.
Example of Built-in Scope
You can access built-in functions without needing to import them:
Summary
- Local Scope: Variables defined within a function are local to that function.
- Enclosing Scope: Variables defined in an outer function can be accessed in a nested function; use
nonlocal
to modify them. - Global Scope: Variables defined at the top level of a script/module are accessible from anywhere in the module; use
global
to modify them within functions. - Built-in Scope: Contains names that are always available in Python.
Understanding variable scope helps you write more organized and error-free code by keeping track of where variables can be accessed and modified.