Python 3.12 retrospective: Build a retryable data transfer with batched
Use itertools.batched from Python 3.12 to bound input chunks, commit each SQLite batch, and verify that failed chunks roll back cleanly.
Archive retrospective · Topic year 2023
In this article
What a small 2023 iterator addition made practical
Python 3.12 introduced itertools.batched. It consumes an iterable as needed and produces tuples of the requested size. Its final tuple may contain fewer items when the input ends. The caller can work with a file reader, generator, or sequence without having to determine the number of items or collect a file’s entire contents before processing starts. This makes the operation a useful building block for a historical data transfer. Grouping input does not determine what is committed. The database transaction defines which writes become visible together, and the record identifier determines whether an already stored record is inserted again. This tutorial gives each of those concerns a concrete role. The five records are small enough to check by hand, so a mismatch in the expected totals has a clear interpretation.
Build a transaction around each of five sample records
Run the example on Python 3.12. An in-memory SQLite table stores a unique record identifier and an integer amount. A database constraint rejects a negative amount. The source list contains five rows. Passing it to batched with a size of two yields A and B, C and D, then E. The source list defines order here. A real file import could use its row ordering, and a query needs an explicit ordering if it relies on a stable restart position. The with db block handles the transaction around one group. When the attempted call containing F and G encounters an invalid amount, the error leaves the block and rolls back the group. Although F is processed before G, neither is left in the table. This demonstrates why a successful first write within an open transaction is not evidence that the whole group reached storage.
from itertools import batched
from sqlite3 import IntegrityError, connect
source = [("A", 10), ("B", 20), ("C", 30), ("D", 40), ("E", 50)]
upsert = """
INSERT INTO counters (record_id, amount)
VALUES (?, ?)
ON CONFLICT (record_id) DO UPDATE
SET amount = excluded.amount
"""
def load_batch(db, batch):
with db:
db.executemany(upsert, batch)
db = connect(":memory:")
db.execute("""
CREATE TABLE counters (
record_id TEXT PRIMARY KEY,
amount INTEGER NOT NULL CHECK (amount >= 0)
)
""")
sizes = []
for batch in batched(source, 2):
load_batch(db, batch)
sizes.append(len(batch))
load_batch(db, (("A", 10), ("B", 20)))
try:
load_batch(db, (("F", 60), ("G", -1)))
except IntegrityError:
print("invalid batch rolled back")
print(sizes)
print(db.execute("SELECT COUNT(*), SUM(amount) FROM counters").fetchone())
db.close()
# invalid batch rolled back
# [2, 2, 1]
# (5, 150)
Model identity before enabling a replay
The first two rows can be submitted again without adding two new records. The SQL uses the primary key to recognise a conflict and updates the record’s stored amount to the supplied one. If A’s amount changes from 10 to 12, the stored row changes to 12. Replaying that same corrected input leaves the result unchanged. A source identifier must therefore represent the same logical record throughout the transfer and its retries. An append-only event feed may require another policy. A conflict between the same identifier and a different amount may represent a changed event, an upstream error, or a valid versioned correction. Whether to preserve original data, store a version, or report the conflict belongs to the application’s data contract. The example models replacement of a record’s current state.
Read the output as evidence
Three successful groups populate sizes with [2, 2, 1]. Their five rows have a combined amount of 150. Resubmitting A and B leaves both values unchanged. The failing group prints a rollback message, and the final query still produces (5, 150). If only F had been saved, the result would instead be (6, 210). The combination of a row count and a total makes the partial write detectable. A source with no rows yields no batches and performs no insert. A source with one row verifies the behavior of a short final group. Another exercise is to correct the failing amount and explicitly resubmit the affected group. When recording an error from a real import, store enough source identity to find the group without exposing the full contents of a private data file in application logs.
Scale cautiously and decide how to resume
The in-memory list makes the result readable. A production CSV import could instead keep the source file open and pass an iterator from the csv module to batched. The group size bounds the number of source rows being processed together. Network libraries, parsers and transformations can allocate extra memory, so field measurements are still needed. A practical choice depends on memory, transaction duration, locking and how much work might have to be repeated after a failure. Small transactions preserve previously committed work. An all-or-nothing import needs a different transaction scope. When a process keeps a resume marker, it can update that marker in the transaction that commits the corresponding group. Bind the location to an identified source version, such as a file digest and line position, so a changed file does not silently invalidate the checkpoint.
Pin the Python version and test the storage behavior
The example intentionally uses the two-argument call available in Python 3.12. Later versions add options that should not be assumed available when revisiting the original release. Accepting a short final batch is the behavior demonstrated here. An application that requires a uniformly sized group can check its length and decide whether to hold or reject it before opening a transaction. The in-memory connection performs actual SQLite writes for the synthetic example. A persistent database adds a useful test: close the connection after a failure, reopen the file, and verify the recorded rows and resume state. A different driver may use different transaction rules or context manager behavior. Run the same successful, repeated and failing groups on the declared target version. Those checks make the transfer’s guarantees visible to readers and future maintainers.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment