dict.clear()
is the easiest, and should be valid, but seems to not actually clear the shelf files (Python 3.5.2, Windows 7 64-bit). For example, the shelf .dat
file size grows every time I run the following snippet, while I would expect it to always have the same size:
shelf = shelve.open('shelf')
shelf.clear()
shelf['0'] = list(range(10000))
shelf.close()
Update: dbm.dumb
, which shelve
uses as its underlying database under Windows, contains this TODO item in its code:
- reclaim free space (currently, space once occupied by deleted or expanded items is never reused)
This explains the ever-growing shelf file problem.
So instead of dict.clear()
, I'm using shelve.open
with flag='n'
. Quoting shelve.open()
documentation:
The optional flag parameter has the same interpretation as the flag
parameter of dbm.open().
And dbm.open()
documentation for flag='n'
:
Always create a new, empty database, open for reading and writing
If the shelf is already open, the usage would be:
shelf.close()
shelf = shelve.open('shelf', flag='n')
dict = { "foo" : "bar"}
should bedict["foo"] = "bar"
. As it is now, it doesn't insert data into the shelf object - instead it pointsdict
to a new dictionary object while leaving the shelf unchanged. – Wandawander