Basics
Object Lifecycle
Two names can refer to the same object. Mutating through one name would affect the object seen through the other.
Source
class Box:
def __init__(self, label):
self.label = label
box = Box("draft")
alias = box
print(box is alias)
print(alias.label)Output
True
draftRebinding box does not change the original object. alias still reaches the first Box until that reference is removed too.
Source
box = Box("published")
print(alias.label)
print(box.label)
del alias
print("old object unreachable")Output
draft
published
old object unreachableNotes
- Assignment binds names to objects; it does not copy the object.
del nameremoves one reference, not necessarily the object itself.- Python reclaims unreachable objects automatically, so lifetime bugs usually come from keeping references longer than intended.
See also
- related: Variables
- prerequisite: Mutability
- next depth: Classes
Run the complete example
Expected output
True
draft
draft
published
old object unreachable
Execution time appears here after you run the example.