A local binding can have the same spelling as a global binding. Inside the function the local one takes precedence; assigning it does not rebind the global name.
color = "blue"
def sign():
color = "green"
return color
print(sign())
print(color)
green
blue
This is shadowing. It can obscure which value is used. A subtle case arises when a function reads a name before assigning it:
count = 3
def increment():
count = count + 1
return count
increment()
Calling increment() raises UnboundLocalError: because the function assigns count, Python treats it as local throughout that function, but the local has no value when the right side is evaluated. Python provides global to explicitly rebind a module global, but passing and returning a value is often easier to reason about:
def increment(count):
return count + 1
count = 3
count = increment(count)
print(count)
4
The caller chooses to rebind its own name. This chapter focuses on module and function scope; nested functions introduce an enclosing scope.