Foundations · Lesson 1 of 18 · 18 min
How Python thinks
Names, objects, and the runtime that binds them.
- Separate names from objects
- Read type, identity, and mutability
- Know what the interpreter actually executes
A language of objects
Python is not a language of boxes that hold values. It is a language of objects floating in a heap, and of names that point at those objects. When you write `x = 3`, you do not put 3 inside x. You create (or reuse) an integer object and bind the name `x` to it.
That single idea explains assignment, function arguments, aliases, and a surprising number of bugs. Two names can point at the same object. Rebinding a name does not change the object. Mutating an object is visible through every name that points at it.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b)
print(a is c)
print(id(a), id(b), id(c))
b.append(4)
print(a)id() is the object's identity. a and b label the same list.
What actually runs
CPython — the interpreter you almost certainly use — compiles source to bytecode, then a stack-based virtual machine executes that bytecode. The `.pyc` files in `__pycache__` are that compiled form. You rarely need to read bytecode, but it is why a syntax error happens before any line runs, and why `def` is an executable statement that creates a function object.
Every value is an object with a type, an identity, and a value. Types themselves are objects (`type(3)` is `int`, and `type(int)` is `type`). This uniformity is why Python can treat classes, functions, and modules as first-class values.
print(type(3))
print(type(int))
print(type(type))
print(isinstance(True, int))
print(dir(3)[:8])Three questions for every value
| Question | Tool | Asks |
|---|---|---|
| What is it? | type(x) | The object's class |
| Who is it? | id(x) / x is y | Identity, not equality |
| What does it contain? | x == y | Value equality |
Mutability is a contract
An object is mutable if its value can change without changing its identity. Lists, dicts, and sets are mutable. Integers, floats, strings, and tuples are not — any 'change' produces a new object and rebinds the name.
Immutability is why strings are safe as dict keys and why a tuple of numbers can be a set element. A tuple is only hashable if every element is hashable, so a tuple that contains a list is immutable in shape but not usable as a key.
Check yourself
Quiz
1.After `a = [1]; b = a; b.append(2)`, what is `a`?
2.Which comparison tests identity, not value?
3.Why is `([1],) ` a valid tuple but not a valid dict key?
Practice
Exercise
Write a function `aliases(a, b)` that returns True when a and b are the same object, and a function `same_value(a, b)` that returns True when they compare equal with ==.
Tutor
Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.