liveBook · Manning

Binding

As explained in The Quick Python Book, Fourth Edition

A binding is an association between an identifier and an object in a namespace.

A binding associates a name with an object in a namespace. Python variables are labels for objects, not containers that hold them. Assignment creates a name when it is first used; no variable type declaration is needed. Types belong to objects, so the same name can later refer to an object of another type. section 4.3 section 1.3.2 section 10.7

Rebinding a name

After `x = "2"`, `x` refers to a string. After `x = int(x)`, it refers to the integer `2`. The name has not acquired a fixed type. section 1.3.2

a = [1, 2, 3]
b = a
c = b
b[1] = 5
print(a, b, c)
[1, 5, 3] [1, 5, 3] [1, 5, 3]

Three names refer to the same list. Changing that list through `b` is visible through `a` and `c` too; this is different from assigning a new object to `b`. section 4.3

Lookup checks the local namespace, then the global namespace, then built-ins. At module level, creating a variable, defining a function, or importing a name adds a binding. A function call creates a local namespace with bindings for its parameters; assignments inside the function add local bindings. A nearer binding can hide a built-in: naming a variable `list` prevents ordinary lookup of the built-in `list`. Deleting a name removes its binding, so looking it up afterward can raise `NameError`. section 10.7 section 4.3

Assignment can bind names to more than simple values:

  • Bind a function to another name and call it through that name; reassignment can select a different function. section 9.5
  • Unpack values into several names at once: `a, b = 1, 2`. Swap their bindings with `a, b = b, a`. section 5.7.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through shared mutable objects, rebinding, namespace lookup, function locals, shadowing, and deletion without descending into interpreter internals.
Examples
Shows a shared list changing through one name, a string name rebound to an integer, and function-local bindings inspected with `locals()`.
What it assumes
Assumes familiarity with variables in other languages while teaching Python’s label-and-namespace model directly.
What you can do after
Diagnose/debug with it when mutation affects several names, lookup selects an unexpected name, or deletion produces `NameError`.
How it connects
Connects binding to assignment, dynamic typing, mutability, function scope, namespaces, imports, and tuple unpacking.

Also explained in

Compare how 11 books explain binding →

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.