Skip to content

04_Names_and_Objects — a name is a binding, not a box

Level: 201 → 301 · for Python programmers, especially ones coming from C, Rust or ABAP

Every assignment in Python points a name at an object and copies nothing. C copies the bytes, ABAP copies the value and Rust moves the ownership; Python does none of those, and almost every surprise in this chapter is that one rule meeting an object that can change: a second name that sees the change, a += that changes the object for everyone who holds it, a "copy" that still shares its insides, and a comparison that answers a different question from the one you asked.

This is the first of the advanced chapters, and it goes first because the others stand on it. A default argument is one object shared by every call, a class attribute is one object shared by every instance, and an iterator is one object that is used up.

# Lesson The question it answers Status
1 Assignment does not copy Why did a change made through b show up in a — and why is [[0] * 3] * 3 one row three times? written
2 += is not + Why did a += [2] change a list I never touched — and why did t[0] += [1] both raise and happen? written
3 is is not == Which of the two comparisons did I mean — and why is int('257') is int('257') a question about CPython, not Python? stub
4 hash() is not stable across runs Why does my set of strings come out in a different order on every run — and why is hash(-1) -2? stub
5 A set is a hash table Why is {True, 1, 1.0} one member, why does a \| (1, 2) fail when a.union((1, 2)) works, and why does a ^ b ^ c keep what is in all three? written
6 Which duplicate survives Why did {k(x): x for x in items} keep the last spelling in the first place, and why does list(set(words)) change order between runs? written
7 A frozenset can be a member Why are there two set types, why does {1, 2} in set_of_frozensets work when d[{1, 2}] does not, and why does \|= on a frozenset leave the other name unchanged? written

Where this sits relative to the other libraries

The Rust library's ownership chapter ↗ is the model this chapter is measured against: A name is not a place ↗ is the half the two languages share, and Copy or move ↗ is the fork Python does not have. The concurrency library ↗ owns what happens when the two names are on two threads, starting with the lost update ↗. Chapter 1's bytearray is the mutable one is this chapter's rule applied to the binary types, and it already carries a kata about +=.