Sub topic 11
Built-in Names and Accidental Shadowing
This chapter assumes you know the LEGB lookup rule, how assignment makes a name local, and how to read a basic traceback. It covers the last scope in the chain, the built-in scope, and the bugs that come from reusing its names.
What the built-in scope contains
The B in LEGB is the built-in scope. It holds the names that exist in every Python program without an import: len, print, list, dict, str, int, sum, max, min, id, type, input, open, the exception classes such as ValueError, and constants such as None and True.
These names live in a module called builtins. You can list them:
import builtins
names = [n for n in dir(builtins) if not n.startswith("_")]
print(len(names) > 100)
print("len" in names, "ValueError" in names)
# Output:
# True
# True TruePython searches this scope last. When a name is not found in the local, enclosing, or global scopes, Python checks builtins. If the name is not there either, you get a NameError.
Shadowing: a closer scope hides a built-in
Shadowing happens when you bind a name that already exists in an outer scope. The new binding is found first, so the outer one becomes unreachable by that name. The built-in is not changed or deleted. Your name just gets found before it.
try:
list = [1, 2, 3]
print(list("abc"))
except TypeError as error:
print(error)
# Output: 'list' object is not callableHere list was assigned at module level. The global scope is searched before the built-in scope, so list("abc") calls your list object instead of the built-in type.
The search stops at the first match. If your module assigned list, the search ends at the global step.
Restoring the built-in
The built-in still exists. Deleting your binding makes the lookup fall through to it again:
import builtins
list = [1, 2, 3]
print(list is builtins.list)
del list
print(list is builtins.list)
print(list("abc"))
# Output:
# False
# True
# ['a', 'b', 'c']Two details matter here. del list removes only the global binding. After it, the name list resolves to the built-in again. Also, builtins.list always gives the original object, which makes it a reliable way to check whether shadowing has happened.
Shadowing inside functions
A local binding shadows a built-in only inside that function. Other code is not affected, so the damage stays small. It can still be confusing, because of the rule from the earlier chapter: any assignment in a function makes that name local for the whole function body.
def average(numbers):
sum = sum(numbers)
return sum / len(numbers)
try:
average([2, 4, 6])
except UnboundLocalError as error:
print(error)
# Output: cannot access local variable 'sum' where it is not associated with a valueThe assignment sum = ... makes sum local everywhere in average. The call sum(numbers) on the right side runs first, and it looks for a local sum that has no value yet. Python does not fall through to the built-in. The wording of the message varies between Python versions.
A common variant does not crash right away. It fails later, when the function uses the built-in after the local assignment:
def describe(values):
max = values[0]
for v in values:
if v > max:
max = v
return max, min(values)
print(describe([3, 9, 4]))
# Output: (9, 3)This works, but it is fragile. Adding a call to max(values) anywhere in the function would raise TypeError, because max is now an integer.
Parameters count as local names
Parameters are local bindings, so a parameter named like a built-in shadows it for the whole function:
def label(id, type):
return f"{type}-{id}"
def broken(items, len):
return len(items)
print(label(7, "user"))
try:
broken([1, 2], 2)
except TypeError as error:
print(error)
# Output:
# user-7
# 'int' object is not callableNaming a parameter id or type is the most common shadowing in real code, because those words are natural. It is harmless until the function body needs the built-in. It also shows up in keyword arguments and in the function's public signature, so callers see the odd name.
Names that are often shadowed
| Name | Typical reason it is reused | Symptom when the built-in is needed later |
|---|---|---|
| `list`, `dict`, `set`, `str` | Naming a variable after its type | `TypeError: 'list' object is not callable` |
| `id`, `type` | Parameter or field names | `TypeError: 'int' object is not callable` |
| `input`, `format` | Holding user data or a format name | `TypeError: 'str' object is not callable` |
| `sum`, `max`, `min` | Running totals and extremes | `UnboundLocalError` or `TypeError` |
| `file`, `open` | Holding a file handle | `TypeError: '_io.TextIOWrapper' object is not callable` |
| `filter`, `map`, `all`, `any` | Holding results | `TypeError` when called again |
The from module import * form can also shadow built-ins without any assignment in your file. For example, the os module exports a function named open, so from os import * replaces the built-in open in your module. Avoid star imports for this reason.
Finding shadowed names in your own module
You can check a namespace against builtins directly. This helper returns the names in a dictionary that collide with a built-in:
import builtins
def shadowed(namespace):
return sorted(
n for n in namespace
if hasattr(builtins, n) and not n.startswith("__")
)
max = 10
id = 7
print(shadowed(globals()))
# Output: ['id', 'max']The startswith("__") filter skips module attributes such as __name__ and __doc__, which exist in both places for unrelated reasons. In practice you should let a linter do this work. The flake8-builtins rules, also implemented in Ruff as the A rule group, report shadowing in variables (A001), function arguments (A002), and class attributes (A003).
What cannot be shadowed
Keywords are different from built-in names. if, class, None, True, and False are reserved by the grammar, so assigning to them is a SyntaxError, not a silent shadow:
try:
compile("None = 5", "<example>", "exec")
except SyntaxError as error:
print("SyntaxError:", error.msg)
# Output: SyntaxError: cannot assign to NoneBuilt-in functions and types such as print and list are ordinary names in a namespace, so Python lets you rebind them. That freedom is what makes accidental shadowing possible.
Avoiding the problem
- Pick a more specific name.
user_idinstead ofid,itemsinstead oflist,totalinstead ofsum. - If the natural word is a built-in, follow the PEP 8 convention of a trailing underscore:
type_,id_,input_. - Turn on the linter rules for shadowing so the editor flags it as you type.
- If you shadowed a built-in at module level in an interactive session, run
del nameto get the original back. - When you must use the built-in and your own name together, reach the built-in explicitly through
import builtinsandbuiltins.list.
Summary
- The built-in scope is the last place Python searches, so any binding in an earlier scope hides it.
- Shadowing never changes the built-in. It only changes what the name finds first.
- In a function, an assignment to a built-in's name makes it local for the whole body, so earlier uses can raise
UnboundLocalError. - Parameters are local bindings too, so parameters named
id,type, orlenshadow those built-ins inside the function. - Linters, specific names, and a trailing underscore prevent nearly all cases.
Exercise
The function below raises an error when called as totallength(["ab", "cde"]). Name the exception, explain why it happens, and give a corrected version. def totallength(words): len = 0; for w in words: len += len(w); return len
Show answer
It raises TypeError: 'int' object is not callable. The assignment len = 0 makes len a local integer, so the call len(w) inside the loop calls an integer instead of the built-in. The fix is to use another name, for example count = 0, then count += len(w), then return count. With that change total_length(["ab", "cde"]) returns 5.
Exercise
A module starts with the line "input = input('Name: ')" and later calls input('Age: '). What happens at the second call, and which two ways would avoid it?
Show answer
The first line works, because the right side is evaluated before the assignment and finds the built-in. After it runs, the global name input holds a string, so the second call raises TypeError: 'str' object is not callable. Avoid it by storing the answer under a different name such as name = input('Name: '), or by deleting the global binding with del input so the built-in is found again.
Exercise
After running "list = [1, 2, 3]" at module level, which expression tells you whether your name still hides the built-in, and what does it return?
Show answer
Use "import builtins" and then "list is builtins.list". It returns False while your list object is bound to the global name. After "del list" it returns True, because the lookup falls through to the built-in scope.