skip to content

With a SQLAlchemy Session, how do you read an object's state with inspect(), and which calls move it between the five states?

level: middleimportance: should knowfreq 35%

answer

  1. InstanceState boolean flags
  2. add, flush, delete, commit
  3. deleted only after the flush
  4. was_deleted survives detachment
  5. make_transient drops the identity key

basics

~20 s

sqlalchemy.inspect(obj) returns the object's InstanceState, whose transient, pending, persistent, deleted and detached flags name its state. add() makes it pending, a flush makes it persistent, delete() plus a flush makes it deleted, and closing the Session or committing the deletion detaches it.

solid answer

~40 s

`inspect(product)` returns an `InstanceState`; exactly one of `.transient`, `.pending`, `.persistent`, `.deleted` and `.detached` is true, and `.key` holds the identity key once the row exists. A new `Product()` is **transient**; `session.add()` makes it **pending**; the flush that INSERTs it makes it **persistent**, as does loading it with a query or `get()`. `session.delete()` only schedules the delete: the object sits in `session.deleted` and stays persistent until the flush sends the DELETE and it becomes **deleted**. Commit then makes it **detached**, while rollback restores it to persistent. `close()` and `expunge()` detach persistent objects. `InstanceState.was_deleted` stays true after a deleted object is detached, and `make_transient()` strips the identity key so the object can be inserted as new.

code

python · 40 lines
python
from sqlalchemy import String, create_engine, inspect
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column


class Base(DeclarativeBase):
    pass


class Product(Base):
    __tablename__ = "product"
    id: Mapped[int] = mapped_column(primary_key=True)
    sku: Mapped[str] = mapped_column(String(20), unique=True)
    stock: Mapped[int]


def state(obj):
    insp = inspect(obj)
    names = ("transient", "pending", "persistent", "deleted", "detached")
    return next(name for name in names if getattr(insp, name))


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)

with Session(engine) as session:
    product = Product(sku="A-5", stock=10)
    print(state(product), inspect(product).key)   # transient None
    session.add(product)
    print(state(product))                         # pending
    session.commit()                              # INSERT, primary key assigned
    print(state(product), inspect(product).key)   # persistent (<class '__main__.Product'>, (1,), None)
    session.delete(product)
    print(state(product))                         # persistent (DELETE not sent yet)
    session.flush()
    print(state(product))                         # deleted
    session.rollback()
    print(state(product))                         # persistent again
    session.delete(product)
    session.commit()
    print(state(product), inspect(product).was_deleted)  # detached True

go deeper

for a junior

Recall the five state names and that inspect(obj) returns an InstanceState whose boolean flags say which one applies.

for a middle

Walk the transitions call by call, especially that delete() leaves the object persistent until the flush, and explain what rollback and commit do to deleted objects.

for a senior

Use inspect() flags, was_deleted and the Session's new, dirty and deleted collections to debug objects that unexpectedly INSERT, vanish or fail to load.

for a principal

Explain when make_transient() or make_transient_to_detached() is a reasonable tool and when a team should prefer an explicit new object or merge().

## Reading the state `sqlalchemy.inspect()` applied to a mapped instance returns its **`InstanceState`**, the object SQLAlchemy uses to track that instance. Its most useful accessors: - **State flags**: `transient`, `pending`, `persistent`, `deleted` and `detached`. Exactly one is `True` at any moment. - **Identity**: `key` (also `identity_key`) is the identity key, `(Product, (5,), None)` for row 5, or `None` while the object has no row; `identity` is just the primary-key tuple; `has_identity` says whether a key exists. - **Ownership**: `session` is the `Session` the object belongs to, or `None`. - **Loading**: `unloaded` and `expired_attributes` name the attributes that would need SQL on access. The Session also exposes its side of the picture: `session.new` (pending objects), `session.dirty` (persistent objects with changes) and `session.deleted` (objects marked with `delete()` but not yet flushed), plus `product in session`. ## The five states | State | How an object gets there | In the identity map | Has an identity key | |---|---|---|---| | transient | constructed, or `make_transient()` | no | no | | pending | `session.add()` of a transient object | no, it is in `session.new` | no, even if `id` was set by hand | | persistent | flushed, or loaded by a query or `get()` | yes | yes | | deleted | `delete()` and then a flush, before the transaction ends | no | yes | | detached | `close()`, `expunge()`, or commit after a delete | no | yes | ## A full cycle, call by call 1. `product = Product(sku="A-5", stock=10)` is **transient**: no Session, no key. 2. `session.add(product)` makes it **pending**. No SQL has run. 3. The flush, on its own or inside `commit()`, sends the INSERT; the object is **persistent** and `inspect(product).key` is filled. 4. `session.delete(product)` puts it in `session.deleted`, but its state is still **persistent**, because no DELETE has been sent. 5. The next flush sends the DELETE; the object is now **deleted**, and it has left the identity map. 6. `rollback()` returns it to **persistent**; `commit()` makes it **detached**, and `inspect(product).deleted` is `False` from then on. ## The subtle cases - **Deleted is short-lived.** It exists only between the flush that sent the DELETE and the end of the transaction. To ask later whether a detached object was deleted, read `InstanceState.was_deleted`, which stays `True` after detachment. - **Rollback undoes an insert, too.** If the transaction that flushed an object's INSERT is rolled back, the object is expunged and goes back to **transient**, with its key cleared, because its row no longer exists. - **Expunge depends on the starting state.** `session.expunge()` sends a persistent object to **detached** and a pending one to **transient**; `expunge_all()` does it for everything, and so does `close()`. - **close() is not rollback().** An object whose INSERT was flushed but never committed comes out of `rollback()` transient, yet comes out of `close()` detached, still carrying an identity key for a row that the closed transaction discarded. - **Detached objects are still readable.** A detached object keeps its loaded values and its identity key; what it cannot do is load an expired or unloaded attribute, which raises `DetachedInstanceError`. - **A primary key set by hand does not make an object persistent.** `Product(id=5, ...)` passed to `add()` is pending and will be INSERTed; the Session does not check whether row 5 exists. ## Using the state in real code - **Tests** can assert that a service left nothing half-done: `inspect(product).persistent` after the call, and an empty `session.new` before the commit. - **Serializers** that receive objects from elsewhere can check `inspect(obj).detached` and `inspect(obj).unloaded` before touching attributes that would need SQL. - **Save helpers** can use `has_identity` to tell an object built in memory (no key, so `add()` will INSERT it) from one that came from a row (key present, so `add()` reattaches it when it is detached). ## make_transient() and make_transient_to_detached() Both live in `sqlalchemy.orm` and are documented as special-case tools: - **`make_transient(product)`** removes the object from its Session, deletes its identity key and resets the deleted flag, keeping every attribute value that is currently loaded. It does not load expired or unloaded attributes first: after the call they read as `None` (or an empty collection). A common use is copying a row: call `make_transient()`, set the primary key to `None`, and `add()` the object to INSERT a new row. - **`make_transient_to_detached(product)`** goes the other way for a transient object whose primary key is set: it builds the identity key, resets the change history as if the object had been loaded, and marks missing attributes as expired. The object can then be added, or merged with `load=False`, without a SELECT.

  • In SQLAlchemy, why does InstanceState.deleted return False for a Product that was deleted and committed earlier?
    The deleted state only lasts from the flush that sent the DELETE until the transaction ends. After `commit()` the object is detached, so `.deleted` is `False` and `.detached` is `True`. `InstanceState.was_deleted` is the accessor that keeps reporting `True` once the object has left the Session.
  • What happens to a SQLAlchemy object whose INSERT was flushed when the transaction is then rolled back?
    The INSERT is undone, so the Session expunges the object and returns it to the transient state: no Session, no identity key. Its Python attribute values remain, so adding it to a Session again schedules a fresh INSERT.

  • Calling session.delete() moves the object into the deleted state at once.
  • A deleted object stays in the identity map until the transaction commits.
  • A pending object has an identity key as soon as add() is called.
  • make_transient() reloads every attribute first, so the copy is complete.
  • A detached object cannot be read at all, even its loaded attributes.