Python variable scope
last modified November 30, 2026 Python 3.15
In this article we explain where variables are visible in Python and how Python finds the value of a name.
The scope of a variable is the part of the program in which
its name can be used. Python has four kinds of scope. A
local scope belongs to a function call. An enclosing
scope is the local scope of an outer function, seen from a nested
function. The global scope belongs to a module, and the
built-in scope holds names such as print and
len. When Python looks up a name, it searches these scopes
in the order local, enclosing, global, built-in, known as the LEGB
rule.
Scopes are created by modules, functions, and classes only. Blocks such
as if and for do not create a new scope.
Local variables
A variable assigned inside a function is local to that function. It exists only while the function runs and cannot be used outside it.
def greet():
message = 'Hello there!'
print(message)
greet()
print(message)
The message variable is created when greet
runs and disappears when the function returns.
greet() print(message)
The call prints the message, but the module-level code does not know
the name and the program fails with a NameError.
$ python local_scope.py
Hello there!
Traceback (most recent call last):
File "/home/user/python/local_scope.py", line 7, in <module>
print(message)
^^^^^^^
NameError: name 'message' is not defined
Reading global variables
A variable assigned at the top level of a module is global. Functions in the module can read it.
rate = 20
def price_with_tax(price):
return price * (100 + rate) / 100
print(price_with_tax(250))
rate = 10
print(price_with_tax(250))
The function uses the global rate variable.
rate = 10 print(price_with_tax(250))
The value is looked up when the function runs, not when it is defined.
After we change rate, the next call uses the new value.
$ python global_read.py 300.0 275.0
Assignment creates a local variable
Assigning to a name inside a function makes that name local, even if a global variable with the same name exists.
count = 10
def reset():
count = 0
print('inside:', count)
reset()
print('outside:', count)
The reset function assigns zero to count.
def reset():
count = 0
print('inside:', count)
The assignment creates a new local variable that hides the global one.
The global count keeps its value. Hiding a name from an
outer scope is called shadowing; see
Python variable shadowing.
To assign to the global variable, the function must declare the name
with the global statement.
$ python same_name.py inside: 0 outside: 10
UnboundLocalError
Python decides which names are local when it compiles a function, not while the function runs. A name assigned anywhere in the function body is local in the whole body.
total = 100
def spend(amount):
print('before:', total)
total = total - amount
return total
spend(30)
The function reads total and assigns to it later.
print('before:', total)
total = total - amount
Because of the assignment on the second line, total is a
local variable in the whole function. The first line reads the local
variable before it has a value, so Python raises
UnboundLocalError; it does not fall back to the global
total.
$ python unbound.py
Traceback (most recent call last):
File "/home/user/python/unbound.py", line 10, in <module>
spend(30)
~~~~~^^^^
File "/home/user/python/unbound.py", line 5, in spend
print('before:', total)
^^^^^
UnboundLocalError: cannot access local variable 'total' where it is not associated with a value
Enclosing scope
A function defined inside another function can read the variables of the outer function. For the inner function, the local scope of the outer function is the enclosing scope.
def make_report(title):
width = 30
def line(text):
print(f'{text:^{width}}')
line(title)
line('-' * len(title))
line('end of report')
make_report('Sales')
The line function centres a text to a given width.
def line(text):
print(f'{text:^{width}}')
The width variable is not local to line, and
it is not global either. Python finds it in the enclosing function
make_report. Inner functions that keep using such
variables after the outer function has returned are closures; see
Python closures. To assign to an
enclosing variable, the inner function needs the
nonlocal statement.
$ python enclosing.py
Sales
-----
end of report
Built-in scope
The built-in functions, exceptions, and constants live in the
builtins module. Its names are available in every module
without an import.
import builtins
print(len('scope'))
print(len is builtins.len)
print(builtins.max([3, 8, 1]))
names = dir(builtins)
print(len(names), 'names in builtins')
for name in names:
if name.startswith('is'):
print(name)
The program looks into the built-in scope.
print(len is builtins.len)
The len name used in our code is the same object as the
len attribute of the builtins module.
names = dir(builtins) print(len(names), 'names in builtins')
The dir function lists the names in the module. Since the
built-in scope is searched last, any of these names can be hidden by a
variable of our own.
$ python builtin_scope.py 5 True 8 163 names in builtins isinstance issubclass
The LEGB rule
When a name exists in several scopes, the innermost one wins. The next example defines the same name at three levels.
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print('inner:', x)
inner()
print('outer:', x)
outer()
print('module:', x)
def outer2():
def inner2():
print('inner2:', x, len)
inner2()
outer2()
Each function assigns its own x.
def inner():
x = 'local'
print('inner:', x)
The inner function finds x in its local
scope. The assignments in inner and outer do
not change the variables of the outer levels.
def inner2():
print('inner2:', x, len)
In inner2, x is not local, and
outer2 does not define it, so Python continues to the
global scope. The name len is found in none of the first
three scopes and comes from the built-in scope.
$ python legb.py inner: local outer: enclosing module: global inner2: global <built-in function len>
No block scope
Unlike C or Java, Python has no block scope. Variables assigned inside
if, for, while, and
with blocks belong to the surrounding function or module.
temperatures = [12, 17, 23, 19]
if temperatures:
first = temperatures[0]
for temp in temperatures:
hot = temp > 20
print('first:', first)
print('temp:', temp)
print('hot:', hot)
for item in []:
seen = item
print('seen' in globals(), 'item' in globals())
The variables are assigned inside the blocks and used after them.
for temp in temperatures:
hot = temp > 20
After the loop, temp holds the last item of the list and
hot the value from the last iteration.
for item in []:
seen = item
print('seen' in globals(), 'item' in globals())
A variable exists only if the assignment has actually run. The loop
over an empty list never assigns item or
seen, so using them would raise a NameError.
List comprehensions are different: their loop variable stays inside
the comprehension; see
Python list comprehensions.
$ python no_block_scope.py first: 12 temp: 19 hot: False False False
Class scope
The body of a class has its own scope. Its names become class attributes, but they are not an enclosing scope for the methods.
class Counter:
start = 10
step = start * 2
def __init__(self):
self.value = Counter.start
def advance(self):
self.value += self.step
return self.value
def broken(self):
return start
c = Counter()
print(Counter.step)
print(c.advance())
print(c.broken())
The class defines two class variables and three methods.
start = 10 step = start * 2
Inside the class body, the names can be used directly, like local variables.
self.value = Counter.start ... self.value += self.step
Methods must reach class variables through the class or through
self.
def broken(self):
return start
A bare start in a method skips the class scope and is
looked up in the global and built-in scopes, where it does not exist.
$ python class_scope.py
20
30
Traceback (most recent call last):
File "/home/user/python/class_scope.py", line 19, in <module>
print(c.broken())
~~~~~~~~^^
File "/home/user/python/class_scope.py", line 13, in broken
return start
^^^^^
NameError: name 'start' is not defined. Did you mean: 'self.start'?
The except clause
The name bound by except ... as is deleted at the end of
the except block, even if it existed before.
error = 'no error yet'
try:
1 / 0
except ZeroDivisionError as error:
message = str(error)
print('message:', message)
print('error:', error)
The program catches a division by zero.
except ZeroDivisionError as error:
message = str(error)
The message variable is an ordinary assignment and stays
available after the block. The error name is removed when
the block ends, so the global error variable we created at
the top is gone too. Python does this so that the exception, which
refers to the stack frames, does not stay in memory. To keep the
exception, assign it to another name inside the block.
$ python except_scope.py
message: division by zero
Traceback (most recent call last):
File "/home/user/python/except_scope.py", line 9, in <module>
print('error:', error)
^^^^^
NameError: name 'error' is not defined. Did you mean: 'OSError'?
The locals and globals functions
The locals function returns the names of the current local
scope, and globals returns the global names of the module.
level = 'module'
def show(a, b=2):
c = a + b
print('locals:', locals())
print('level' in locals(), 'level' in globals())
show(1)
for name in list(globals()):
if not name.startswith('__'):
print('global:', name)
The program prints the local variables of a function and the global names of the module.
print('locals:', locals())
print('level' in locals(), 'level' in globals())
Inside a function, locals returns a new dictionary with
the parameters and local variables; changing it does not change the
variables. A global name such as level is not in it.
for name in list(globals()):
The globals function returns the live dictionary of the
module. The loop assigns the global variable name, which
adds a key to that dictionary, so we iterate over a copy. Iterating over
the dictionary itself would raise a RuntimeError. The
names that start with two underscores, such as __name__,
are set by Python for every module.
$ python inspect_scopes.py
locals: {'a': 1, 'b': 2, 'c': 3}
False True
global: level
global: show
Source
Naming and binding, builtins – Built-in objects, locals
In this article we have explained local, enclosing, global, and
built-in scopes, the LEGB lookup order, why assignment makes a name
local and leads to UnboundLocalError, the absence of block
scope, the scope of class bodies and except clauses, and
the locals and globals functions. See also
Python variables,
Python variable shadowing,
Python global keyword, and
Python nonlocal keyword.
Author
List all Python tutorials.