What is Python scope?
Python scope refers to the region of the code where a variable is accessible. There are four scopes in Python:
Examples:
Local scope:
Python
def my_function():
local_variable = 10
print(local_variable)
my_function()
Output:
10
The local_variable variable is only accessible within the my_function() function. It is not accessible outside of the function.
Global scope:
Python
global_variable = 10
def my_function():
print(global_variable)
my_function()
Output:
10
The global_variable variable is accessible anywhere in the program, including inside the my_function() function.
Enclosing scope:
Python
def outer_function():
enclosing_variable = 10
def inner_function():
print(enclosing_variable)
inner_function()
outer_function()
Output:
10
The enclosing_variable variable is defined in the outer function, but it is accessible in the inner function.
Built-in scope:
Python
print(len("Hello, world!"))
Output:
12
The len() function is a built-in function in Python. It is accessible anywhere in the program, without having to import it.
Scope resolution
When Python tries to access a variable, it first looks for it in the local scope. If the variable is not found in the local scope, Python then looks for it in the enclosing scope, and so on. If the variable is not found in any of the scopes, Python then raises a NameError.
Changing the scope of a variable
You can change the scope of a variable using the global keyword. If you declare a variable inside a function and want to make it accessible outside of the function, you can use the global keyword before the variable name.
For example:
Python
def my_function():
global global_variable
global_variable = 10
my_function()
print(global_variable)
Output:
10
In this example, the global_variable variable is declared inside the my_function() function, but it is made accessible outside of the function using the global keyword.
Conclusion
Python scope is an important concept to understand in order to write efficient and maintainable code. By understanding how Python scope works, you can avoid errors and write more concise code.