Sub topic 1
Names, Objects, and Identity
Prerequisites
This chapter assumes basic Python syntax, including functions, classes, lists, and dictionaries. You should also know how to run a Python script or use the interactive interpreter. The examples assume CPython, the usual Python implementation.
Names, objects, and identity
A Python variable is a name bound to an object. The object stores the value and has an identity, type, and state. Assignment usually binds a name; it does not copy the object.
The is operator checks whether two names refer to the same object. The == operator checks whether their values compare as equal.
a = [1]
b = a
print(a is b) # True
print(a == b) # True
c = list(a)
print(a is c) # False
print(a == c) # TrueMutability and aliasing
A mutable object can change after creation. Lists and dictionaries are mutable. Integers, strings, and tuples are generally immutable.
Aliasing occurs when multiple names refer to one object. A mutation through either name is visible through all aliases.
a = [1]
b = a
b.append(2)
print(a) # [1, 2]
print(a is b) # TrueUse list(a) or a.copy() when you need a shallow copy. Nested objects remain shared in a shallow copy.
Reference counting: how most objects are freed
In CPython, each object tracks references to it. When the reference count reaches zero, CPython usually releases the object immediately.
import sys
a = []
print(sys.getrefcount(a)) # Includes a temporary reference
b = a
print(sys.getrefcount(a))
del b
print(sys.getrefcount(a))sys.getrefcount() itself temporarily adds a reference, so its result is one higher than the count you normally expect. Reference counting cannot by itself reclaim objects that reference one another in a cycle. The cyclic garbage collector handles those cycles.
Object lifetime, `del`, and finalizers
del name removes a name binding. It does not necessarily destroy the object. The object remains alive while another strong reference points to it.
When an object is finalized, Python may call its __del__ method. Avoid relying on __del__ for important cleanup because timing can be unpredictable, especially with cycles and interpreter shutdown. Prefer context managers such as with open(...) for files and other resources.
Exercise
After b = a; del a, does the list necessarily disappear?
Show answer
No. The list remains alive because b still refers to it.