dict.clear() is the simplest and should be valid, but apparently doesn't actually clear the shelf files (Python 3.5.2, Windows 7 64-bit). For example, the size of the .dat shelf file grows every time I run the following snippet, while I expect it to always be the same size:
shelf = shelve.open('shelf') shelf.clear() shelf['0'] = list(range(10000)) shelf.close()
Update: dbm.dumb , which shelve uses as the base database for Windows, contains this TODO element in its code :
- return free space (currently the space occupied by deleted or extended items is never reused)
This explains the ever-growing problem with files in shelves.
So instead of dict.clear() I use shelve.open with flag='n' . Quoting shelve.open() documentation :
The optional flag parameter has the same interpretation as the dbm.open () parameter flag.
And dbm.open() documentation for flag='n' :
Always create a new, empty database open for reading and writing.
If the shelf is already open, use will be:
shelf.close() shelf = shelve.open('shelf', flag='n')
source share