Local, Global, and Nonlocal Variables Scope
Deslize para mostrar o menu
Understanding how Python determines the scope of variables is crucial for writing clear and bug-free code. Python uses a specific set of rules, known as the LEGB rule, to decide where it should look for the value of a variable. LEGB stands for Local, Enclosing, Global, and Built-in. When you reference a variable, Python searches for its value in this order:
- Local: variables defined within the current function or method;
- Enclosing: variables in the nearest enclosing function scope (if using nested functions);
- Global: variables defined at the top level of the module or declared global using the
globalkeyword; - Built-in: names that are preassigned in Python, such as
lenorrange.
This rule allows Python to resolve variable names efficiently and helps you predict where a variable's value will come from. Sometimes, you may want to modify variables outside the current function's scope. Python provides two keywords for this: global and nonlocal. The global keyword lets you assign a value to a variable at the module level, while nonlocal allows you to modify a variable in the nearest enclosing function scope that is not global.
123456789101112131415161718# Global scope global_var = "I am global" def outer(): # Enclosing scope enclosing_var = "I am enclosing" def inner(): # Local scope local_var = "I am local" print("Local:", local_var) print("Enclosing:", enclosing_var) # Found in enclosing scope print("Global:", global_var) # Found in global scope print("Built-in:", len([1, 2, 3])) # 'len' comes from built-in scope inner() outer()
- The variable
global_varis defined at the global scope and is accessible from anywhere in the module; - Inside the
outerfunction,enclosing_varcreates an enclosing scope variable that can be accessed by nested functions; - The nested
innerfunction defineslocal_var, which exists only within that function and demonstrates access to variables from all enclosing scopes; - The
lenfunction is used to show how Python can access names from the built-in scope.
It shows how Python finds variable values by searching through local, enclosing, global, and built-in scopes in that order, making variable resolution predictable and organized.
1. What does the nonlocal keyword do in Python?
2. What is the LEGB rule?
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo