liveBook · Manning

Binding

As explained in Get Programming: Learn to code with Python

An association between a name and the object to which that name refers.

Binding gives an object a name you can use later. In Python, that name is a variable: it refers to the object, so you can use its value without recalculating it. Think of naming something in a room instead of describing it every time. section 4.2 section 4.0

Bind a name to a result

`a = 1` gives the name `a` to an object with value 1. After `b = 2`, the line `c = a + b` evaluates the expression on the right to 3 and binds `c` to that result. The `=` sign assigns a value; it does not ask Python to solve an equation as it would be read in math class. section 4.2 section 4.1

A name can later refer to a different object. Run `a = 1` and then `a = 2`: `a` now refers to the object with value 2. This changes the binding, not the value of the original integer object. section 24.1

Figure 24.1. The variable named a is bound to an object with value 1 in one memory location. When the variable named a is bound to a different object with value 2, the original object with value 1 is still in memory; you just can’t access it anymore through a variable.

Follow the name `a` as it moves from the object with value 1 to the object with value 2. section 24.1

More than one name can also refer to the same mutable object, such as a list or dictionary. Those names are aliases: changing the object through either name affects what both names refer to. Choose descriptive names so the role of each value is clear. section 28.0 section 2.4

Use names in a small program

In a minutes converter, `minutes_to_convert = 123` names the input. Calculated results are stored under names such as `hours_part` and `minutes_part` before they are printed. Quick check: which name would you change to try a different input? section 6.2 section 6.4

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines binding through assignment examples, then traces rebinding through an immutable-object memory diagram.
Examples
Walks through `a = 1`, `b = 2`, `c = a + b`, reassignment, and a minutes-conversion program.
What it assumes
Introduces variables from everyday naming rather than assuming prior programming experience.
What you can do after
Build it from scratch: initialize descriptive variables, use them in calculations, and recognize when reassignment changes a name’s binding.
How it connects
Connects binding to expressions, immutable objects, mutable objects, and aliasing.

Also explained in

Compare how 11 books explain binding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.