diff options
Diffstat (limited to 'Doc/library/dbm.rst')
-rw-r--r-- | Doc/library/dbm.rst | 38 |
1 files changed, 22 insertions, 16 deletions
diff --git a/Doc/library/dbm.rst b/Doc/library/dbm.rst index 81a05c7..f5496d5 100644 --- a/Doc/library/dbm.rst +++ b/Doc/library/dbm.rst @@ -73,33 +73,39 @@ Key and values are always stored as bytes. This means that when strings are used they are implicitly converted to the default encoding before being stored. +These objects also support being used in a :keyword:`with` statement, which +will automatically close them when done. + +.. versionchanged:: 3.4 + Added native support for the context management protocol to the objects + returned by :func:`.open`. + The following example records some hostnames and a corresponding title, and then prints out the contents of the database:: import dbm # Open database, creating it if necessary. - db = dbm.open('cache', 'c') + with dbm.open('cache', 'c') as db: - # Record some values - db[b'hello'] = b'there' - db['www.python.org'] = 'Python Website' - db['www.cnn.com'] = 'Cable News Network' + # Record some values + db[b'hello'] = b'there' + db['www.python.org'] = 'Python Website' + db['www.cnn.com'] = 'Cable News Network' - # Note that the keys are considered bytes now. - assert db[b'www.python.org'] == b'Python Website' - # Notice how the value is now in bytes. - assert db['www.cnn.com'] == b'Cable News Network' + # Note that the keys are considered bytes now. + assert db[b'www.python.org'] == b'Python Website' + # Notice how the value is now in bytes. + assert db['www.cnn.com'] == b'Cable News Network' - # Often-used methods of the dict interface work too. - print(db.get('python.org', b'not present')) + # Often-used methods of the dict interface work too. + print(db.get('python.org', b'not present')) - # Storing a non-string key or value will raise an exception (most - # likely a TypeError). - db['www.yahoo.com'] = 4 + # Storing a non-string key or value will raise an exception (most + # likely a TypeError). + db['www.yahoo.com'] = 4 - # Close when done. - db.close() + # db is automatically closed when leaving the with statement. .. seealso:: |