summaryrefslogtreecommitdiffstats
path: root/Doc/library/dbm.rst
diff options
context:
space:
mode:
authorNick Coghlan <ncoghlan@gmail.com>2013-11-17 05:59:51 (GMT)
committerNick Coghlan <ncoghlan@gmail.com>2013-11-17 05:59:51 (GMT)
commitc610aba1ed57a30104a254ccd1f9fe07d02b1334 (patch)
treede690ad2f0b0f9cda831d66f026e5494a77882c5 /Doc/library/dbm.rst
parenteb8ea265bac16844efebe4f42d3c674527a66988 (diff)
downloadcpython-c610aba1ed57a30104a254ccd1f9fe07d02b1334.zip
cpython-c610aba1ed57a30104a254ccd1f9fe07d02b1334.tar.gz
cpython-c610aba1ed57a30104a254ccd1f9fe07d02b1334.tar.bz2
Close #19282: Native context management in dbm
Diffstat (limited to 'Doc/library/dbm.rst')
-rw-r--r--Doc/library/dbm.rst38
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::