Lesson 21 of 52Objects
The Python Memory Model
See names as labels on objects, so aliasing, mutation, copying and argument passing never surprise you again.
"I changed one list and another one changed too." Almost every Python developer hits this bug, and it shows up again in code review, in debugging sessions and in interviews. The cure is one mental model: names are labels attached to objects, not boxes that hold values. Once you see it, a whole family of bugs becomes obvious.
Everything is an object
In Python, every value is an object: numbers, strings, lists, functions, classes, even None. Every object has three things:
- an identity: which object it is, which never changes (
id(x)shows it as a number), - a type: what kind of object it is (
type(x)), - a value: the data it holds.
Press Run (⌘ Enter) to see what happens.Even functions and classes are objects. That is why you can store a function in a list or pass a class to another function.
Names point to objects
An assignment like a = [1, 2] does two things: it creates a list object, then it binds the name a to it. The name is a label. Writing b = a does not copy anything. It attaches a second label to the same object.
Python builds a list object and binds the name a to it.
That last step holds the key distinction of this lesson:
- Mutating changes the object itself (
append,x[0] = ...,d["k"] = ...,.sort()). Every name pointing to it sees the change. - Rebinding points a name at a different object (
x = ...). Other names are unaffected.
What does this print?
a = [1, 2, 3] b = a b[0] = 99 b = [0] print(a)
Identity vs equality: is vs ==
== asks "do these have the same value?" and calls __eq__. is asks "are these the same object?" and compares identities. Two separate lists can be equal without being identical.
Press Run (⌘ Enter) to see what happens.Use is only for singletons, objects of which only one exists: None, True, False. For everything else use ==.
result has no value?Mutable and immutable types
Some types can never change after creation. They are immutable: int, float, bool, str, tuple, frozenset, bytes, None. Operations on them build new objects. Others are mutable and can change in place: list, dict, set, and most objects of your own classes.
Two names, one string object.
What does this print?
a = (1, 2) b = a a += (3,) x = [1, 2] y = x x += [3] print(len(b), len(y))
Passing arguments: by object reference
Is Python "pass by value" or "pass by reference"? Neither, exactly. When you call f(x), the parameter inside the function becomes another name for the same object. This is often called pass by assignment or pass by object reference: it is exactly as if the function ran param = x first.
So the same two rules apply. If the function mutates the object, the caller sees it. If the function rebinds its parameter, the caller does not.
Press Run (⌘ Enter) to see what happens.This explains the famous mutable default argument bug. A default value is evaluated once, when def runs, and that one object is reused on every call.
Press Run (⌘ Enter) to see what happens.def clear(d): d = {} is called as clear(config). What is config afterwards?Shallow vs deep copy
When you do want an independent copy, you have two levels:
- A shallow copy (
list(x),x[:],x.copy(),dict(d),copy.copy(x)) creates a new outer container, but its items are the same objects as before. - A deep copy (
copy.deepcopy(x)) recursively copies everything inside too.
For a flat list of numbers, a shallow copy is enough. For nested data (a list of lists, a dict of lists) a shallow copy still shares the inner objects.
The outer list holds references to two row lists.
Press Run (⌘ Enter) to see what happens.Order these from 'shares the most' to 'shares the least' with the original nested list x.
- Tap the steps below in the right order.
How memory is freed
You never free memory by hand in Python. CPython, the standard interpreter, uses reference counting: every object tracks how many references point to it. When the count drops to zero (the last name is rebound or goes out of scope, or the container holding it is gone), the object is freed immediately.
Reference counting alone cannot free cycles: two objects that point to each other keep each other's count above zero. So CPython also runs a cyclic garbage collector (the gc module) every so often to find and free groups of objects that only reference each other.
Press Run (⌘ Enter) to see what happens.del x deletes the name, not the object. The object goes away only when nothing else refers to it.
Under the hood: small int caching
CPython creates the integers from -5 to 256 once at startup and reuses them, because they are used everywhere. So a = 100; b = 100; a is b is True, while the same test with bigger numbers may be True or False depending on how the code was compiled. Short strings that look like identifiers are often reused too (interning).
a = 256
b = 256
a is b # True in CPython, but do not rely on itThis is an implementation detail of CPython, not part of the language. Other interpreters may differ, and the exact behaviour can change between versions. The lesson: never use is to compare numbers or strings. Use ==.
Fix the mutable default
This function has the classic mutable default argument bug: calls that do not pass tags all share one list.
add_tag("a") # ["a"]
add_tag("b") # should be ["b"], but the buggy version returns ["a", "b"]Fix add_tag so that:
- when
tagsis not passed, each call starts from a new empty list, - when the caller passes their own list, the tag is appended to that list (mutating it) and the same list is returned.
Clone a grid
Write clone_grid(grid) that returns a copy of a 2D list (a list of rows) that is fully independent: changing a cell in the copy must never change the original, and vice versa.
g = [[1, 2], [3, 4]]
c = clone_grid(g)
c[0][0] = 99
g # still [[1, 2], [3, 4]]A shallow copy like grid.copy() is not enough, because the rows would still be shared. Try it without the copy module.
- name binding
- Attaching a name to an object.
b = abinds a second name to the same object; nothing is copied. - mutation vs rebinding
- Mutation changes an object in place (seen by every alias). Rebinding points one name at a different object.
- is vs ==
ischecks identity (same object);==checks value via__eq__. Useisonly forNone,True,False.- pass by assignment
- Function parameters are new names for the caller's objects, as if
param = argran first. - shallow vs deep copy
- Shallow copies the outer container only;
copy.deepcopycopies nested objects too. - reference counting
- CPython frees an object as soon as no references remain; a cyclic GC handles reference cycles.