Sub topic 1
Names, objects, and identity
Every later chapter in this tutorial depends on one idea: in Python, a variable is a name that refers to an object. It is not a box that holds a value. This chapter builds that model and shows how to test it with id(), is, and ==. It also covers the mistakes the model prevents.
Prerequisites
This chapter assumes you can do the following:
- Write Python functions, classes, lists, and dictionaries.
- Run scripts or use the interactive interpreter.
- Accept that the code here runs on CPython, the standard interpreter from python.org.
Some outputs below are CPython implementation details. They are labeled as such, and you should not depend on them in real programs.
Objects come first, names second
Every value in a Python program is an object. Integers, strings, lists, functions, classes, and modules are all objects. Each object has three properties:
- Identity: a number that distinguishes it from every other object that exists at the same time. It never changes during the object's life.
- Type: what kind of object it is, which determines what operations it supports.
- Value: the data it holds. For a mutable object, the value can change.
A name is a label in a namespace that refers to an object. The statement x = 42 does not copy 42 into a place called x. It creates an integer object (or finds an existing one) and binds the name x to it. The statement is called an assignment, but it is really a binding.
Several names can refer to the same object. An object can also exist with no name at all, as when you call print([1, 2, 3]).
Names live in namespaces
A namespace maps names to objects. Module-level names live in a dictionary that you can inspect:
x = "hello"
print(globals()["x"]) # hello
print(globals()["x"] is x) # TrueLocal variables, instance attributes, and class attributes work the same way. Instance attributes are stored in obj.__dict__. Other places also hold references to objects, not copies. These include list items, dictionary keys and values, tuple elements, closure cells, and function arguments.
This matters for memory management. An object stays alive as long as something refers to it. A name is only one kind of reference.
Reading identity with `id()` and `is`
The built-in id(obj) returns the object's identity as an integer. In CPython, this integer is the object's memory address. The is operator compares identities directly:
a = [1, 2, 3]
b = a
print(id(a) == id(b)) # True
print(a is b) # TrueThe expression a is b is true exactly when id(a) == id(b). It is faster, because it compares two addresses and runs no user code.
Identity is only unique while the object lives
Two objects that exist at the same time never share an id. After an object is freed, a new object can reuse its address and therefore its id:
first = id([1, 2, 3]) # the temporary list is freed right after id() returns
second = id([4, 5, 6]) # a new list may land at the same address
print(first == second) # often True in CPython, but not guaranteedThe result is often True, which shows why you must never store an id() value and use it later as proof that an object is the same. The old object may be gone and a different one may sit at that address. If you need to track an object without keeping it alive, use a weak reference, covered in a later chapter.
Identity versus equality
Two different questions can be asked about two names:
| Question | Operator | What it checks |
|---|---|---|
| Are they the same object? | `is` | Identity |
| Do the objects have equal values? | `==` | Calls `__eq__` on the objects |
a = [1, 2]
b = [1, 2]
print(a == b) # True: same value
print(a is b) # False: two separate list objectsThe == operator can be redefined by a class. The is operator cannot, so it always means the same thing.
Use is for singletons. The standard case is None, because there is exactly one None object:
def describe(value=None):
if value is None:
return "nothing given"
return f"got {value!r}"
print(describe()) # nothing given
print(describe(0)) # got 0Writing if value is None is more precise than if not value, which also treats 0, "", and [] as missing. It also cannot be fooled by a class that defines an unusual __eq__.
Do not use is to compare numbers or strings. Whether two equal values are the same object depends on the interpreter's caching rules:
p = int("1000")
q = int("1000")
print(p == q) # True
print(p is q) # False in CPython: two separate int objects
r = int("100")
s = int("100")
print(r is s) # True in CPython: small integers are cachedCPython keeps a cache of small integers (from -5 to 256), so equal small ints share one object. This is an optimization, not a language rule. The chapter on interning and caching explains it. The practical lesson here is that is on values gives results that differ between interpreters and versions.
Assignment never copies
Binding a new name to an existing object does not duplicate the object:
original = {"count": 0}
alias = original
alias["count"] += 1
print(original) # {'count': 1}
print(alias is original) # TrueTo get a separate object, you must create one explicitly, for example with dict(original), original.copy(), or copy.deepcopy(original). The next chapter covers copying and aliasing in detail. Here, the point is that the model "names refer to objects" predicts the output without any special cases.
Rebinding versus mutating
Two operations look similar but do different things:
- Rebinding changes which object a name refers to:
x = something_else. No object is modified. - Mutating changes the object itself, through a method or item assignment such as
x.append(1)orx[0] = 5. Every name bound to that object sees the change.
a = [1]
b = a
a = a + [2] # builds a new list and rebinds a; b is unaffected
print(a, b) # [1, 2] [1]
a = [1]
b = a
a += [2] # for lists, += mutates the existing object in place
print(a, b) # [1, 2] [1, 2]The two forms a = a + [2] and a += [2] give the same value for a but different results for b. The + operator on lists creates a new list. The += operator calls list.__iadd__, which extends the existing list. This is a common source of confusion, and the names-and-objects model explains it.
Function calls pass references to objects
When you call a function, each parameter name is bound to the argument object. This is sometimes described as "pass by object reference" or "pass by assignment." The function does not receive a copy, and it cannot rebind the caller's name.
def rebind(items):
items = [0] # rebinds the local name only
def mutate(items):
items.append(0) # changes the shared object
data = [1, 2]
rebind(data)
print(data) # [1, 2]
mutate(data)
print(data) # [1, 2, 0]Inside rebind, the local name items first refers to the caller's list and is then rebound to a new list. The caller's data still refers to the original. Inside mutate, both names refer to the same list, so the change is visible to the caller.
Removing a name with `del`
The del statement removes a name from its namespace. It does not delete the object:
a = [1, 2, 3]
b = a
del a
print(b) # [1, 2, 3]
try:
print(a)
except NameError as error:
print(error) # name 'a' is not definedAfter del a, the list still exists because b refers to it. An object is freed only when nothing refers to it anymore. The next chapters explain how CPython tracks this.
Common errors
- Using
isfor value comparison.x is 1000can be false even whenx == 1000. Use==for values andisonly forNone,True,False, and deliberate identity checks. Python warns aboutiswith a literal at compile time. - Expecting assignment to copy.
b = amakes a second name for the same object. If you later change one, you change both. - Storing
id()values. An id is valid only while its object lives. Saving one and comparing later can match a different object. - Assuming a function can rebind your variable. It cannot. It can only mutate the object you passed in.
- Treating
del xas freeing memory. It removes one reference. Memory is released only when the last reference is gone.
Exercise
Predict the output of the code below, and explain each line using names, objects, and identity. x = [1, 2] y = x z = list(x) y.append(3) print(x, z) print(x is y, x is z, x == z)
Show answer
The first line prints [1, 2, 3] [1, 2]. Assigning y = x binds a second name to the same list, so y.append(3) changes the object that x also refers to. The call list(x) creates a new list object bound to z, so z keeps its old value [1, 2]. The second line prints True False False. The names x and y refer to one object, so x is y is true. The names x and z refer to different objects, so x is z is false. After the append, the values [1, 2, 3] and [1, 2] differ, so x == z is also false.
Exercise
A function is defined as def reset(items): items = []. A caller runs data = [1, 2, 3]; reset(data); print(data). What does it print, and how would you change reset so that the caller's list becomes empty?
Show answer
It prints [1, 2, 3]. The assignment items = [] only rebinds the local name items to a new empty list, and the caller's name data still refers to the original list. To empty the caller's list, mutate the object instead, for example with items.clear() or items[:] = [].