Sub topic 1
Names Refer to Objects: What Binding Means
Prerequisites
Assume you can define and call Python functions, assign values, use lists, and read a simple traceback. This chapter establishes the scope model needed for later work with closures and global.
Names Refer to Objects
A Python variable is a name, not a box that permanently contains a value. A name is bound when it is associated with an object. Assignment binds a name to an object:
message = "hello"
other = message
print(message)
print(other)Both names refer to the same string object. Reassigning message changes its binding, but it does not change other:
message = "goodbye"
print(message) # goodbye
print(other) # helloThe object and the name are separate ideas. This distinction becomes important when a function uses a name from outside itself.
Namespaces and Scopes
A namespace is a mapping from names to objects. A scope is the part of a program where a namespace can be searched directly.
Common namespaces include:
- The local namespace created while a function runs.
- The global namespace belonging to a module.
- The built-in namespace containing names such as
lenandprint.
flowchart TD
A[Name used in code] --> B[Local namespace]
B --> C[Global module namespace]
C --> D[Built-in namespace]
D --> E[Object found]The same name can exist in several namespaces. Python chooses the name visible in the current scope according to its lookup rules.
Local Names Inside a Function
A name assigned inside a function is normally local to that function. Each call receives its own local namespace:
def describe():
item = "local"
print(item)
describe()
# print(item) here would raise NameErrorThe name item exists while describe runs. It is not automatically available at module level. Local names prevent separate function calls from accidentally sharing ordinary assignments.
Global Names at Module Level
A name assigned outside functions belongs to the module’s global namespace. A function can read that name when it has no local name with the same spelling:
label = "module value"
def show_label():
print(label)
show_label()
# Output: module valueThe function reads the global label; it does not create a local label. Rebinding a global from inside a function follows different rules and requires explicit treatment.
Exercise
Where is item bound in def f(): item = 3?
Show answer
It is bound in the local namespace created when f runs.