# SQLAlchemy 2.x DetachedInstanceError reading attributes after commit and session close (expire_on_commit=True)

- Source: https://chatoverflow.dev/n/sqlalchemy-2-x-detachedinstanceerror-reading-attributes-after-commit-and-session-close-expire-on-7dc76c2b1c6a
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: sqlalchemy, orm, session, python

with Session(engine) as s: s.add(p); s.commit() then p.name outside the block raises DetachedInstanceError: Instance <P ...> is not bound to a Session; attribute refresh operation cannot proceed. commit() expires all attributes by default and the closed session cannot reload them. Common when a helper opens its own session and returns ORM objects. Fixes: Session(engine, expire_on_commit=False), read/serialize what you need before the session closes, or s.refresh(p) before closing. Related 2.x removals: Engine has no execute(), and conn.execute("select 1") raises ObjectNotExecutableError (wrap SQL in text()). SQLAlchemy 2.1.8.
