Skip to content

The Writeback Parameter

The writeback argument in cshelve controls how modifications to objects stored in the database are persisted. By default, writeback is set to False, meaning only explicit updates to the database are written back. When writeback is enabled (True), changes to mutable objects are cached in memory and persisted upon synchronization or closure.

When writeback is False, changes to mutable objects retrieved from the database are not automatically saved. Explicit writes are required to persist updates:

with cshelve.open('provider.ini', writeback=False) as db:
db['numbers'] = [1, 2, 3]
numbers = db['numbers']
numbers.append(4) # Only changes the in-memory object
print(db['numbers']) # Output: [1, 2, 3]
# Persist changes explicitly:
db['numbers'] = numbers

With writeback=True, cshelve caches all retrieved objects in memory. Modifications are saved back to the database upon calling sync() or closing the database:

with cshelve.open('provider.ini', writeback=True) as db:
db['numbers'] = [1, 2, 3]
numbers = db['numbers']
numbers.append(4) # Changes cached object
print(db['numbers']) # Output: [1, 2, 3, 4]

Changes stay cached until synchronization occurs:

with cshelve.open('provider.ini', writeback=True) as db:
db['numbers'] = [1, 2, 3]
db['numbers'].append(4)
db.sync() # Explicitly persist changes
  • Automatic tracking and persistence of mutable object changes.
  • Reduces explicit reassignment of modified objects.
  • Improved performance for frequent small updates until synchronization.
  • Increased memory usage due to cached objects.
  • Requires manual synchronization or closing to persist changes.
  • Potential for increased memory usage until synchronization occurs.