liveBook · Manning

Reference

As explained in The Quick Python Book, Fourth Edition

An object reference is a binding or pointer-like association through which a name identifies a runtime object.

In Python, a variable is a label that refers to an object rather than a container holding a value. Several labels can refer to the same object, and assignment changes which object a label refers to. section 4.3

Reference behavior becomes visible through assignment and mutation:

  • Assigning a mutable object to another name creates another reference; mutating the object is visible through every name. section 4.3
  • Assigning a new immutable value changes only the assigned name's reference; other names still refer to the original object. section 4.3
  • A name can refer to objects of different types at different times, such as a string followed by an integer. section 4.3

Mutation versus reassignment

With a list, `a = [1, 2, 3]`, `b = a`, and `c = b` make all three names refer to one object; `b[1] = 5` therefore produces `[1, 5, 3]` through each name. With integers, `a = 1`, `b = a`, and `b = 5` leave `a` referring to `1` while `b` refers to `5`.

Function arguments are passed by object reference: a parameter becomes a new reference to the argument's object. Mutating a passed list affects the caller's object, but rebinding the parameter does not; immutable values likewise remain unchanged outside the function. section 9.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through mutable and immutable assignment and function-parameter effects, but does not descend into interpreter implementation.
Examples
Uses aliased lists, reassigned integers, and a function that mutates one list while reassigning another parameter.
What it assumes
Assumes general programming knowledge and develops the distinction between mutable and immutable object behavior.
What you can do after
Diagnose whether assignment or mutation will affect other names and function callers.
How it connects
Connects variables, assignment, mutable objects, immutable objects, function parameters, and aliasing.

Also explained in

Compare how 17 books explain reference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.