Python scope determines where a name (variable, function, class) is visible and how it is looked up when referenced. In functions, name lookup follows the LEGB rule: Local, Enclosing, Global, Built-in. This means Python searches the local scope first, then any enclosing functions, then the module-level global scope, and finally the built-in scope.
Formula
The lookup order is not a mathematical formula but a rule: Local → Enclosing → Global → Built-in. When you reference a name like x inside a function, Python checks the local namespace (the function’s own scope). If not found, it checks the enclosing scopes (outer functions, if any). Then the global namespace (the module). Finally, the built-in namespace (like print or len). The first match wins.
Worked Example
Consider the calculator above: you enter a global x (default 10) and a local y (default 5). The function adds them. With defaults, the result is 15. In Python:
x = 10 # global
def add(y):
return x + y # x is global, y is local
print(add(5)) # 15
Here, x is not defined locally, so Python looks in the global scope and finds 10. y is a parameter, so it is local. The sum is 15.
Background: Why Scope Matters
Scope prevents name collisions and makes code predictable. Without scoping, a variable in one function could accidentally overwrite another’s. Python’s design uses namespaces (dictionaries) to store names. Each function call creates a new local namespace. This is why recursive functions work—each call has its own set of locals.
How Name Lookup Works Step by Step
- Local: The function’s own namespace. Includes parameters and variables assigned with
=inside the function. - Enclosing: If the function is nested inside another function, Python checks the outer function’s local scope. This is how closures work.
- Global: The module’s namespace. Variables defined at the top level of a file.
- Built-in: Python’s built-in names like
print,len,range.
If a name is not found in any scope, Python raises a NameError.
How to Choose: Local vs Global Variables
Use local variables for temporary data that only the function needs. This keeps the global namespace clean and avoids unintended side effects. Use global variables for constants or shared state that many functions need. However, modifying a global variable inside a function requires the global keyword; otherwise, Python treats the assignment as creating a new local variable.
Common Problems and Misconceptions
- UnboundLocalError: If you assign to a variable anywhere in a function, Python treats it as local throughout the function. Referencing it before assignment raises an error.
- Modifying a global without
global: You can read a global, but assigning to it creates a local. Useglobal xto modify the global. - Mutable globals: You can modify a global list or dict without
globalbecause you are not rebinding the name—you are mutating the object. - LEGB is not dynamic: The lookup order is determined at compile time, not runtime. This means the scope of a name is fixed when the function is defined, not when it is called.
Comparisons: Python vs Other Languages
Unlike C or Java, Python has no block-level scope (e.g., inside if or for). Variables created inside a block are still function-scoped. Python’s LEGB is similar to JavaScript’s scope chain but simpler—JavaScript has function scope and block scope with let/const. Python’s nonlocal keyword is like JavaScript’s closure variable access, but explicitly declared.
Costs and Performance Implications
Name lookups are fast because namespaces are dictionaries. Local lookups are the fastest because they are indexed by position in CPython. Global lookups are slower because they require a dictionary lookup. Built-in lookups are the slowest because they require a global lookup first, then a built-in lookup. For performance-critical loops, assign frequently used globals to local variables.
Safety and Best Practices
- Avoid using
globalexcessively; it makes code hard to debug. - Use descriptive variable names to avoid shadowing built-ins (e.g., don’t name a variable
list). - Prefer passing values as arguments and returning results over relying on globals.
- Use
nonlocalin nested functions to modify enclosing variables.
Alternatives and Advanced Techniques
For shared state across functions, consider classes or modules. For dynamic scoping, Python does not support it natively, but you can simulate with context variables or explicit dictionaries. For performance, you can use locals() to access the local namespace, but it is rarely needed.
Frequently Asked Questions
What is the difference between local and global scope?
Local scope is the namespace inside a function; variables defined there are only accessible within that function. Global scope is the module-level namespace; variables defined there are accessible anywhere in the module, but must be declared global to be modified inside a function.
Why do I get UnboundLocalError even though I have a global variable?
If you assign to a variable anywhere in a function, Python considers it local for the entire function. If you reference it before the assignment, you get UnboundLocalError. To fix, either use global x or avoid the assignment.
How does nonlocal work?
nonlocal is used in nested functions to refer to a variable in the enclosing function’s scope. It allows you to modify that variable without making it global. For example, a counter in an outer function can be incremented by an inner function using nonlocal count.
Can I access a function’s local variables from outside?
Not directly. However, you can return them or use attributes on the function object (e.g., func.my_var = 5). In debugging, you can use locals() inside the function, but that is not a normal access pattern.
What is the built-in scope?
The built-in scope contains Python’s built-in functions and exceptions like print, len, ValueError. It is the last place Python looks. You can shadow built-ins by defining your own names, but that is generally bad practice.
Does Python have block scope?
No. Variables defined inside an if, for, or while block are still in the function’s local scope. They are accessible after the block ends. This is different from languages like C or Java.
Related
Formula used
in x | Global x | - | 10 | 0 in y | Local y | - | 5 | 0 out result | Sum of x and y | - | x + y | 0
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- DisplayPort vs HDMI: Which Cable Should You Use?
- Soundbar vs 2.1 Speaker System: Which Is Better?
- Survive Lava for Brainrot Tier List170 points
- MySQL Dump Import: Fix Common Errors
- Mouse Moving on Its Own? Causes & Fixes
- Slack Channels for Construction Projects: Setup Guide