Avoid Shadowing Outer and Built-in Names
Core idea
Shadowing happens when a binding in a nearer scope has the same name as a binding in an outer scope. It changes which object a name denotes, not the hidden object. A local parameter can intentionally shadow a global, but accidental shadowing makes code hard to read.
label = "warehouse"def display(label): return label.upper()print(display("desk"))print(label)The parameter label refers to desk. The outer label remains warehouse.
Intentional failure: mask a built-in
def report(): len = 4 return len("tea")report()The integer bound to len is not callable, so the call fails.
Choose a descriptive name
def report(): max_length = 4 return len("tea") <= max_lengthprint(report())The name max_length avoids hiding len and describes the threshold.
Common mistake
Names such as list, sum and str are legal variable names, but using them for unrelated values masks useful built-ins. Renaming is clearer than working around the collision.
Practice
Write a function with a local variable named sum, predict why sum([1, 2]) fails, then repair it with a descriptive variable name.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Diagnose name shadowing
Check your understanding of shadowing.
What is printed?
label = "store"def f(label): return labelprint(f("desk"))Which exception occurs?
def f(): len = 2 return len("abc")f()What is printed?
def f(): max_length = 2 return len("abc")print(f())How should an accidental built-in name collision usually be repaired?