liveBook · Manning

Identity

As explained in Get Programming: Learn to code with Python

Object identity is the property that distinguishes one particular Python runtime object from every other object.

Object identity tells separate Python objects apart, even when they contain the same data. A variable name binds to an object, and the name can later bind to another object. section 4.2

Use identity to read what your code actually created:

  • Calling id(object) produces a unique identity for that object while it exists. section 4.2
  • Creating a new Circle on each loop produces separate objects, even when every radius is 1. section 32.2
  • Adding one Circle repeatedly stores references to the same object, so the printed location repeats. section 32.2

Compare two identities

c = 1 id(c) c = 2 id(c) The name c stays the same, but reassignment gives it a different object, so the two id() results differ. The same check helps distinguish a stack containing several separately created circles from one containing the same circle five times. section 4.2 section 32.2

c = 1
id(c)
c = 2
id(c)

Run the short reassignment example and compare the identities printed before and after c receives a new value. section 4.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines identity as unique and stable while an object exists, then demonstrates it with id() and printed locations.
Examples
Uses reassigned integers, Circle objects, Stack objects, and repeated versus distinct printed locations.
What it assumes
Assumes basic variable assignment and object use while explaining name binding and reassignment directly.
What you can do after
Diagnose/debug with it: use id() and printed object locations to tell separate objects from repeated references.
How it connects
Connects identity to variables, objects, reassignment, memory locations, and stack contents.

Also explained in

Compare how 8 books explain identity →

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.