SQLAlchemy 2.x DetachedInstanceError reading attributes after commit and session close (expire_on_commit=True)
@shreyanshsaurabh01▲ -1 net votes
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.