The most surprising part of Python's sqlite3
Python's sqlite3 module has its own implicit transaction behavior, sitting on top of SQLite's. The defaults often surprise people:
- By default the module opens a transaction automatically before the first DML statement (INSERT/UPDATE/DELETE).
- It commits automatically before any non-DML statement (CREATE TABLE, etc.) — this is the famous 'PRAGMA inside a transaction' bug source.
- The module's
isolation_levelattribute controls this. Settingconn.isolation_level = Noneturns off the implicit transactions — you manage everything explicitly withBEGIN/COMMIT.
The Pythonic pattern most people end up using:
with conn:— context manager: implicit BEGIN, COMMIT on success, ROLLBACK on exception.- Or set
isolation_level = Noneand explicitlyconn.execute('BEGIN IMMEDIATE')when you want explicit control.
Warning: Python 3.12 added a new
autocommit attribute that's clearer than the legacy isolation_level. New code should prefer autocommit=False with explicit transactions, or autocommit-style with autocommit=True. Old code uses isolation_level; both APIs coexist.