I need a quick refresher on variable scope in python.
- User
I need a quick refresher on variable scope in python.
- Assistant
Of course! Here is a quick but thorough refresher on variable scope in Python.
The Core Idea
Scope is the set of rules that determines where in your code a variable can be accessed or "seen." It prevents variables in different parts of your program from accidentally interfering with each other.
Python uses a rule called LEGB to resolve which variable you're referring to. It checks for the variable in the following order:
- Local
- Enclosing
- Global
- Built-in
Let's break each of these down.
The 4 Scopes (LEGB Rule)
1. Local (L)
This is the innermost scope. Any variable you define inside a function is local to that function. It's created when the function is called and destroyed when the function finishes.
def my_function(): x = 10 # x is in the Local scope of my_function print(x) my_function() # Prints 10 # print(x) # NameError: name 'x' is not defined outside the function2. Enclosing (E)
This scope only exists for nested functions. If a function is defined inside another function, the inner function can access variables from the outer (enclosing) function.
def outer_function(): y = 20 # y is in the Enclosing scope for inner_function def inner_function(): # inner_function can "see" y from the outer scope print(y) inner_function() # Prints 20 outer_function()3. Global (G)
This is the top-level scope of your Python script. Any variable defined outside of all functions is in the global scope. It can be accessed from anywhere in your code (but not necessarily modified).
z = 30 # z is in the Global scope def another_function(): # This function can READ the global variable z print(z) another_function() # Prints 30 print(z) # Prints 304. Built-in (B)
This is the widest scope. It contains all the names that are pre-loaded into Python, like the
print(),len(),str(),list, andsumfunctions, and exceptions likeValueError. Python checks this scope last.
Keywords for Modifying Scope:
globalandnonlocalBy default, you can only read variables from outer scopes. If you try to assign a new value to a variable that exists in an outer scope, Python will create a new local variable instead.
To explicitly modify variables in outer scopes, you use the
globalandnonlocalkeywords.The
globalKeywordUse
globalto tell a function that you want to modify a variable in the global scope.count = 0 # Global variable def increment(): # Without 'global', this would create a NEW local variable named 'count' # and would raise an UnboundLocalError if you tried `count = count + 1` global count count = count + 1 print(f"Inside function: {count}") increment() # Inside function: 1 increment() # Inside function: 2 print(f"Outside function: {count}") # Outside function: 2The
nonlocalKeywordUse
nonlocalto tell an inner function that you want to modify a variable in its enclosing scope (but not the global scope).def outer(): count = 0 # Enclosing scope variable def inner(): # Without 'nonlocal', this would create a NEW local variable 'count' nonlocal count count += 1 print(f"Inside inner: {count}") inner() inner() print(f"Inside outer: {count}") outer() # Output: # Inside inner: 1 # Inside inner: 2 # Inside outer: 2
Common Pitfalls & "Gotchas"
-
UnboundLocalError: This happens when you try to modify a global/enclosing variable without using
globalornonlocal. Python sees the assignment (=) and assumes it's a new local variable, but then you try to read from it on the right side before it's been assigned.x = 10 def my_func(): # This will fail because Python sees `x = ...` and treats `x` # as a local variable, but it hasn't been defined yet locally. x = x + 1 # UnboundLocalError -
No Block Scope: Python does not have scope for
if,for, orwhileblocks like C++ or JavaScript. Variables defined in a loop are available outside the loop.for i in range(5): pass print(i) # Prints 4. The variable 'i' "leaked" out of the loop. -
Shadowing Built-ins: Be careful not to name your variables the same as a built-in function. This is a common mistake.
# BAD practice: list = [1, 2, 3] # You just overwrote the built-in list() function! # my_new_list = list("hello") # TypeError: 'list' object is not callable
Summary Table
Scope How It's Defined Keyword to Modify Key Characteristic Local Inside a function - Default scope for variables created in a function. Enclosing In a nested function (the outer function) nonlocalExists only when functions are nested. Global At the top-level of a module/script globalAccessible from anywhere in the file. Built-in Pre-defined in Python ( print,len, etc.)- (Don't!) Always available, represents Python's core library.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.