Chapter 6. Object References, Mutability, and Recycling
“You are sad,” the Knight said in an anxious tone: “let me sing you a song to comfort you. […] The name of the song is called ‘HADDOCKS’ EYES’.”
“Oh, that’s the name of the song, is it?” Alice said, trying to feel interested.
“No, you don’t understand,” the Knight said, looking a little vexed. “That’s what the name is CALLED. The name really IS ‘THE AGED AGED MAN.’”
Adapted from Lewis Carroll, Through the Looking-Glass, and What Alice Found There
Alice and the Knight set the tone of what we will see in this chapter. The theme is the distinction between objects and their names. A name is not the object; a name is a separate thing.
We start the chapter by presenting a metaphor for variables in Python: variables are labels, not boxes. If reference variables are old news to you, the analogy may still be handy if you need to explain aliasing issues to others.
We then discuss the concepts of object identity, value, and aliasing. A surprising trait of tuples is revealed: they are immutable but their values may change. This leads to a discussion of shallow and deep copies. References and function parameters are our next theme: the problem with mutable parameter defaults and the safe handling of mutable arguments passed by clients of our functions.
The last sections of the chapter cover garbage collection, the del
command,
and a selection of tricks that Python plays with immutable objects.
This is a rather dry chapter, but its topics ...
Get Fluent Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.