(4, True, b'Wham!')
>>> file.close() # close sometimes required
Internally, importing the dbm standard library module automatically loads whatever
DBM interface is available in your Python interpreter (attempting alternatives in a fixed
order), and opening the new DBM file creates one or more external files with names
that start with the string 'movie' (more on the details in a moment). But after the import
and open, a DBM file is virtually indistinguishable from a dictionary.
In effect, the object called file here can be thought of as a dictionary mapped to an
external file called movie; the only obvious differences are that keys must be strings (not
arbitrary immutables), and we need to remember to open to access and close after
changes.
Unlike normal dictionaries, though, the contents of file are retained between Python
program runs. If we come back later and restart Python, our dictionary is still available.
Again, DBM files are like dictionaries that must be opened:
C:\...\PP4E\Dbase> python
>>> import dbm
>>> file = dbm.open('movie', 'c') # open existing DBM file
>>> file['Batman']
b'Pow!'
>>> file.keys() # keys gives an index list
[b'Cat-woman', b'Batman', b'Joker', b'Robin']
>>> for key in file.keys(): print(key, file[key])
...
b'Cat-woman' b'Splat!'
b'Batman' b'Pow!'
b'Joker' b'Wham!'
b'Robin' b'Bang!'
Notice how DBM files return a real list for the keys call; not shown here, their values
method instead returns an iterable view like dictionaries. Further, DBM files always
store both keys and values as bytes objects; interpretation as arbitrary types of Unicode
text is left to the client application. We can use either bytes or str strings in our code
when accessing or storing keys and values—using bytes allows your keys and values
to retain arbitrary Unicode encodings, but str objects in our code will be encoded to
bytes internally using the UTF-8 Unicode encoding by Python’s DBM implementation.
Still, we can always decode to Unicode str strings to display in a more friendly fashion
if desired, and DBM files have a keys iterator just like dictionaries. Moreover, assigning
and deleting keys updates the DBM file, and we should close after making changes (this
ensure that changes are flushed to disk):
>>> for key in file: print(key.decode(), file[key].decode())
...
Cat-woman Splat!
Batman Pow!
Joker Wham!
1306 | Chapter 17: Databases and Persistence