ZetCode

Python variable shadowing

last modified November 30, 2026 Python 3.15

In this article we show how names in Python can hide other names, and how to recognize and avoid the bugs this causes.

Shadowing happens when a name defined in an inner scope has the same name as one in an outer scope. While the inner name exists, the outer one cannot be reached by its plain name. Python looks up names in the order local, enclosing, global, and built-in, as described in Python variable scope, so a local variable shadows a global one, and any variable shadows a built-in function of the same name.

Shadowing is not an error, and sometimes it is harmless. It becomes a bug when we later need the hidden name, typically a built-in function such as list, id, or type.

Local names shadow global names

Parameters and local variables shadow global variables with the same name.

local_global.py
name = 'Ada'


def greet(name):
    print(f'Hello there, {name}!')


def farewell():
    name = 'Grace'
    print(f'Goodbye, {name}!')


greet('Linus')
farewell()
print('global name:', name)

Both functions use the name name, which also exists globally.

def greet(name):
    print(f'Hello there, {name}!')

Inside greet, name is the parameter. The global variable is hidden, but not changed.

def farewell():
    name = 'Grace'

The assignment creates a local variable. After both calls, the global name still refers to 'Ada'.

$ python local_global.py
Hello there, Linus!
Goodbye, Grace!
global name: Ada

Shadowing a built-in

Built-in names are looked up last, so a variable of our own hides them. Programs often use names such as list, dict, str, sum, or max for data.

builtin_list.py
list = [3, 1, 2]
print(sorted(list))

letters = list('abc')
print(letters)

We store numbers in a variable called list.

list = [3, 1, 2]
print(sorted(list))

Up to here, the program works.

letters = list('abc')

Now list is our list object, not the built-in type, and a list cannot be called. The error appears far from the line that caused it, which makes the bug hard to find in a longer program.

$ python builtin_list.py
[1, 2, 3]
Traceback (most recent call last):
  File "/home/user/python/builtin_list.py", line 4, in <module>
    letters = list('abc')
TypeError: 'list' object is not callable

Restoring a built-in

A shadowed built-in is still available in the builtins module, and deleting our variable makes the built-in visible again.

restore_builtin.py
import builtins

list = [3, 1, 2]
print(list)
print(builtins.list('abc'))

del list
print(list('abc'))

The program reaches the built-in list in two ways.

print(builtins.list('abc'))

The builtins module always holds the original objects.

del list
print(list('abc'))

The del statement removes our global variable. Python no longer finds list in the global scope and falls back to the built-in scope. The built-in itself was never changed.

$ python restore_builtin.py
[3, 1, 2]
['a', 'b', 'c']
['a', 'b', 'c']

Parameters named after built-ins

Parameter names such as id, type, input, and format look natural, but they hide the built-ins in the whole function body.

parameter_names.py
def label(id, type):
    if not isinstance(id, int):
        kind = type(id).__name__
        raise TypeError(f'id must be an int, not {kind}')
    return f'{type} #{id}'


print(label(7, 'ticket'))
print(label('7', 'ticket'))

The label function builds a label such as ticket #7 and validates the id.

kind = type(id).__name__

The function wants to report the type of the wrong id. But type is the string parameter, so the error handling itself fails with a different error than intended. The first call works, because the line runs only for invalid input; such bugs often hide in rarely used code paths.

The usual fix is a different name, such as kind or item_type, or a trailing underscore: type_ and id_.

$ python parameter_names.py
ticket #7
Traceback (most recent call last):
  File "/home/user/python/parameter_names.py", line 9, in <module>
    print(label('7', 'ticket'))
          ~~~~~^^^^^^^^^^^^^^^
  File "/home/user/python/parameter_names.py", line 3, in label
    kind = type(id).__name__
           ~~~~^^^^
TypeError: 'str' object is not callable

Shadowing a function

Functions are stored in variables like any other value. Assigning the result of a function to its own name replaces the function.

function_name.py
def total(prices):
    result = 0
    for price in prices:
        result += price
    return result


total = total([4, 5, 6])
print(total)

print(total([1, 2]))

The program sums a list of prices.

total = total([4, 5, 6])

The right side runs first and calls the function. Then the result, an integer, is bound to the name total. The second call tries to call the integer.

$ python function_name.py
15
Traceback (most recent call last):
  File "/home/user/python/function_name.py", line 11, in <module>
    print(total([1, 2]))
          ~~~~~^^^^^^^^
TypeError: 'int' object is not callable

Nested functions

In nested functions, the parameters and local variables of the inner function shadow those of the outer function.

nested.py
def outer():
    size = 10
    unit = 'cm'

    def inner(size):
        unit = 'mm'
        print('inner:', size, unit)

    inner(size * 10)
    print('outer:', size, unit)


outer()

The inner function has a parameter called size and a local variable called unit.

def inner(size):
    unit = 'mm'

Both names shadow the variables of outer. The assignment to unit creates a new local variable, so the outer unit stays 'cm'.

$ python nested.py
inner: 100 mm
outer: 10 cm

Loop variables

A for loop does not create a new scope. Its variable does not shadow an existing variable; it overwrites it.

loop_variable.py
name = 'report.txt'

files = ['a.csv', 'b.csv']
for name in files:
    print('processing', name)

print('saving to', name)

for i in range(3):
    for i in range(2):
        pass
    print('outer i:', i)

The program uses the name name twice for different purposes.

for name in files:
    print('processing', name)

print('saving to', name)

After the loop, name holds the last file name, and the output file name is lost.

for i in range(3):
    for i in range(2):
        pass
    print('outer i:', i)

The inner loop reuses i. Both loops still run the right number of times, because each loop takes its next value from its own range, but after the inner loop, i is always 1.

$ python loop_variable.py
processing a.csv
processing b.csv
saving to b.csv
outer i: 1
outer i: 1
outer i: 1

Imports

An import binds names in the global scope and can hide built-ins. This happens most easily with star imports, which bring in names we do not see.

import_shadow.py
from os import *

with open('notes.txt', 'w') as f:
    f.write('first line\n')

The program wants to write a text file.

from os import *

The os module has its own low-level open function, which takes integer flags and returns a file descriptor. The star import replaces the built-in open with it, and the error message does not mention that the wrong function is called. Import the module instead, as in import os, and use os.open when we really want it.

$ python import_shadow.py
Traceback (most recent call last):
  File "/home/user/python/import_shadow.py", line 3, in <module>
    with open('notes.txt', 'w') as f:
         ~~~~^^^^^^^^^^^^^^^^^^
TypeError: 'str' object cannot be interpreted as an integer

File names that shadow modules

The directory of the script is searched first when importing. A file with the name of a standard library module hides that module. We have a project with two files.

project/random.py
def roll():
    return 4

The random.py file was created for some experiment with dice.

project/game.py
import random

print(random.randint(1, 6))

The game.py program imports random and calls randint.

import random

The import finds project/random.py before the standard library. Our module has no randint. Since Python 3.13, the error message points out the conflicting file. The fix is to rename the file; file names such as random.py, email.py, json.py, or test.py should be avoided.

$ python project/game.py
Traceback (most recent call last):
  File "/home/user/python/project/game.py", line 3, in <module>
    print(random.randint(1, 6))
          ^^^^^^^^^^^^^^
AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/user/python/project/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

Instance attributes

Attribute lookup on an object checks the instance first and then the class. An instance attribute therefore shadows a class attribute or a method with the same name.

attributes.py
class Account:
    currency = 'EUR'

    def __init__(self, owner):
        self.owner = owner

    def summary(self):
        return f'{self.owner} ({self.currency})'


a = Account('Jan')
b = Account('Eva')
b.currency = 'USD'

print(a.summary(), b.summary(), Account.currency)

a.summary = 'no summary'
print(a.summary)
print(b.summary())
print(a.summary())

The Account class has a class attribute currency and a method summary.

b.currency = 'USD'

The assignment creates an instance attribute in b. It shadows the class attribute for b only; a and the class still see 'EUR'.

a.summary = 'no summary'

Here the instance attribute shadows the method. For a, summary is now a string, and calling it fails, while b still has the method.

$ python attributes.py
Jan (EUR) Eva (USD) EUR
no summary
Eva (USD)
Traceback (most recent call last):
  File "/home/user/python/attributes.py", line 20, in <module>
    print(a.summary())
          ~~~~~~~~~^^
TypeError: 'str' object is not callable

Finding shadowed built-ins

We can check a namespace for names that also exist in the builtins module.

find_shadowed.py
import builtins

list = [1, 2]
id = 42
input_file = 'data.txt'


def shadowed(namespace):
    found = []
    for name in namespace:
        if hasattr(builtins, name) and not name.startswith('__'):
            found.append(name)
    return found


print('module:', shadowed(globals()))


def process(type, values, max=10):
    print('function:', shadowed(locals()))


process('csv', [])

The shadowed function takes a dictionary of names, such as the result of globals or locals.

if hasattr(builtins, name) and not name.startswith('__'):

The hasattr function tells whether the builtins module has an attribute of that name. We skip the special names such as __name__, which every module defines. The global input_file is fine; only exact names count.

$ python find_shadowed.py
module: ['list', 'id']
function: ['type', 'max']

Source

Resolution of names, builtins – Built-in objects, Built-in functions

In this article we have shown how parameters, local variables, nested functions, loop variables, imports, file names, and instance attributes shadow other names, which errors this produces, how to reach and restore a shadowed built-in, and how to look for shadowed names. See also Python variable scope, Python variables, and Python global keyword.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.