Sub topic 1
Names Refer to Objects: What Binding Means
Scope rules answer the question "which variable does this name mean?" Before that question makes sense, you need an accurate picture of what a Python "variable" is. This chapter builds that picture. Later chapters on local, global, and enclosing scopes depend on it.
Prerequisites
This chapter assumes you can:
- define and call a function in Python
- use assignment and
print - work with lists and basic data types such as
intandstr - read a simple traceback
You do not need to know anything about scope rules yet.
The working model: names, objects, bindings
In Python, a variable is not a box that holds a value. Instead, there are two separate things:
- An object is a value living in memory, such as the integer
5, a string, or a list. Every object has a type and an identity. - A name is a label that refers to an object. A binding is the link between a name and an object.
A statement like x = 5 does not put 5 inside x. It creates the object 5 (or finds an existing one) and binds the name x to it. The type belongs to the object. The name has no type and can later be bound to an object of any type.
x = 5
print(type(x))
x = "five"
print(type(x))
# Output:
# <class 'int'>
# <class 'str'>The name x is the same in both cases. Only its binding changed.
Assignment binds, it does not copy
When the right-hand side of an assignment is a name, Python does not duplicate the object. It binds a second name to the same object.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
print(a is b)
# Output:
# [1, 2, 3, 4]
# TrueBoth names refer to one list. The is operator tests whether two names refer to the same object. The == operator tests whether the objects have equal values. Two separate lists [1] and [1] are == but not is.
The built-in id() returns a number that identifies an object while it exists. You can use it to confirm that two names share an object.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(id(a) == id(b))
print(a == c)
print(a is c)
# Output:
# True
# True
# FalseRebinding leaves the old object alone
Assigning to a name that already exists changes which object the name refers to. It does not modify the object it used to refer to.
a = [1, 2, 3]
b = a
a = [9]
print(a)
print(b)
print(a is b)
# Output:
# [9]
# [1, 2, 3]
# FalseThe first assignment bound a to a new list. The name b still refers to the original. This distinction between rebinding a name and mutating an object is central to scope. A later chapter shows that a function can mutate a global list freely but cannot rebind the global name without extra syntax.
An object stays alive as long as at least one name, or another object, refers to it. When nothing refers to it, Python can reclaim its memory.
Augmented assignment: rebinding or mutating?
The += operator behaves differently depending on the type. For immutable objects such as integers, it computes a new object and rebinds the name. For a list, it mutates the list in place.
n = 1
m = n
m += 1
print(n, m)
a = [1]
b = a
b += [2]
print(a, b)
# Output:
# 1 2
# [1, 2] [1, 2]For the integers, m += 1 rebound m to the new object 2, and n kept 1. For the lists, b += [2] extended the shared list, so a sees the change. In both cases, += also finishes with a rebinding of the name to the result. Keep that in mind: it explains an error you will meet in a later chapter.
Many statements bind names
Assignment with = is only one of the ways to create a binding. Each of these also binds a name:
| Statement | Name it binds |
|---|---|
| `import math` | `math` |
| `def greet(): ...` | `greet` |
| `class Point: ...` | `Point` |
| `for i in range(3): ...` | `i` |
| `with open(p) as f: ...` | `f` |
| `except ValueError as err: ...` | `err` |
| `(n := 10)` | `n` |
| Function parameters | each parameter name |
The following program shows several of these at module level. It also shows an edge case: the name after except ... as is removed when the except block ends.
import math
def greet():
return "hi"
class Point:
pass
for i in range(3):
pass
if (n := 10) > 5:
pass
try:
1 / 0
except ZeroDivisionError as err:
print("caught", type(err).__name__)
for name in ["math", "greet", "Point", "i", "n", "err"]:
print(name, name in globals())
# Output:
# caught ZeroDivisionError
# math True
# greet True
# Point True
# i True
# n True
# err FalseThe loop variable i still exists after the loop ends, which surprises people coming from other languages. The name err does not survive its except block. Python deletes it automatically to avoid keeping the exception and its traceback alive.
The function globals() returns a dictionary of the names bound at module level. This hints at how Python stores names, which the next chapter covers.
Function arguments are bindings too
Calling a function binds each parameter name to the object you passed in. Nothing is copied. Inside the function, the parameter and the caller's name refer to the same object until one of them is rebound.
def add_and_reset(items):
items.append("x")
items = []
items.append("y")
return items
data = []
result = add_and_reset(data)
print(data)
print(result)
# Output:
# ['x']
# ['y']The call items.append("x") mutates the caller's list. Then items = [] rebinds the parameter to a new list, and the caller's data is unaffected. The second append changes only the new list. This behavior is sometimes called "pass by object reference" or "pass by assignment". It follows directly from the binding model.
Removing a binding with del
The del statement removes a name. It does not destroy an object directly.
a = [1]
b = a
del a
print(b)
print("a" in globals())
# Output:
# [1]
# FalseAfter del a, the name a no longer exists, but the list survives because b still refers to it. Using a now would raise a NameError.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Changing one list also changes another | `b = a` bound a second name to the same object | Make a copy, for example `b = a.copy()` or `b = list(a)` |
| `a is b` is `False` for equal values | `is` tests identity, not equality | Use `==` to compare values |
| Function changes the caller's list unexpectedly | The parameter refers to the caller's object, and the function mutated it | Copy the argument inside the function, or return a new object |
| Function "ignores" a reassignment of its parameter | Rebinding a parameter does not affect the caller's name | Return the new object and bind it in the caller |
| `NameError` after an `except ... as err` block | Python removes `err` when the block ends | Copy the value to another name inside the block if you need it |
A shallow copy such as a.copy() creates a new outer list but binds its elements to the same objects as the original. For nested structures, mutating an inner object is still visible through both lists. The standard library function copy.deepcopy copies the nested objects too.
What comes next
You now have the vocabulary the rest of the tutorial uses: a name is a label, an object is the thing it refers to, and a binding connects them. Python keeps its bindings in structures called namespaces, and the next chapter explains how they are organized and how scope decides which one a name belongs to.
Exercise
What does this code print, and why? a = [1, 2] b = a b += [3] c = a c = c + [4] print(a, b, c)
Show answer
It prints [1, 2, 3] [1, 2, 3] [1, 2, 3, 4]. The statement b = a binds b to the same list as a. The statement b += [3] mutates that shared list in place, so a and b both show [1, 2, 3]. The statement c = a also binds c to the shared list, but c = c + [4] builds a new list and rebinds c to it, leaving the shared list unchanged.
Exercise
A function is defined as def reset(items): items = []. You call reset(data) where data = [1, 2, 3]. What is data afterward, and how would you change the function so the caller's list ends up empty?
Show answer
data is still [1, 2, 3], because items = [] only rebinds the parameter name to a new list. To empty the caller's list, mutate the object instead: use items.clear() (or items[:] = []) inside the function.