Python Scope
In Python, scope refers to the region in a program where a particular variable is accessible and can be referenced. It defines the visibility and lifetime of variables and other named entities in your code.
Python has the following types of scopes:
- Local scope: Variables defined within a function have a local scope. They are only accessible within that specific function. Once the function execution is complete, the local variables are destroyed. Local variables can shadow variables with the same name in outer scopes, meaning they take precedence within the function.
- Enclosing scope: This scope applies to nested functions. If a variable is not found in the local scope of a nested function, Python looks for it in the enclosing scope, which is the scope of the outer function. This process continues until the variable is found or the global scope is reached.
- Global scope: Variables defined at the top level of a module or explicitly declared as global within a function have a global scope. They are accessible throughout the module or the function, respectively. Global variables can be accessed from any part of the code.
- Built-in scope: This is the widest scope in Python and includes built-in functions, such as
print()
,len()
, andrange()
, as well as built-in types likestr
andlist
. These entities are always available without the need for import statements.
When accessing a variable, Python searches for it in the local scope first, then in any enclosing scopes, followed by the global scope, and finally in the built-in scope. This search process is known as the “LEGB” rule.
Here’s an example to illustrate Python scope:
python
x = 10 # Global variable
def foo():
y = 20 # Local variable
print(x) # Accessing global variable
print(y) # Accessing local variable
foo()
print(x) # Accessing global variable outside the function
Output:
10
20
10
In this example, x
is a global variable accessible within the function foo()
as well as outside of it. The variable y
is a local variable only accessible within the foo()
function.