@@ -73,33 +73,39 @@ Key and values are always stored as bytes. This means that when
7373strings are used they are implicitly converted to the default encoding before
7474being stored.
7575
76+ These objects also support being used in a :keyword: `with ` statement, which
77+ will automatically close them when done.
78+
79+ .. versionchanged :: 3.4
80+ Added native support for the context management protocol to the objects
81+ returned by :func: `.open `.
82+
7683The following example records some hostnames and a corresponding title, and
7784then prints out the contents of the database::
7885
7986 import dbm
8087
8188 # Open database, creating it if necessary.
82- db = dbm.open('cache', 'c')
89+ with dbm.open('cache', 'c') as db:
8390
84- # Record some values
85- db[b'hello'] = b'there'
86- db['www.python.org'] = 'Python Website'
87- db['www.cnn.com'] = 'Cable News Network'
91+ # Record some values
92+ db[b'hello'] = b'there'
93+ db['www.python.org'] = 'Python Website'
94+ db['www.cnn.com'] = 'Cable News Network'
8895
89- # Note that the keys are considered bytes now.
90- assert db[b'www.python.org'] == b'Python Website'
91- # Notice how the value is now in bytes.
92- assert db['www.cnn.com'] == b'Cable News Network'
96+ # Note that the keys are considered bytes now.
97+ assert db[b'www.python.org'] == b'Python Website'
98+ # Notice how the value is now in bytes.
99+ assert db['www.cnn.com'] == b'Cable News Network'
93100
94- # Often-used methods of the dict interface work too.
95- print(db.get('python.org', b'not present'))
101+ # Often-used methods of the dict interface work too.
102+ print(db.get('python.org', b'not present'))
96103
97- # Storing a non-string key or value will raise an exception (most
98- # likely a TypeError).
99- db['www.yahoo.com'] = 4
104+ # Storing a non-string key or value will raise an exception (most
105+ # likely a TypeError).
106+ db['www.yahoo.com'] = 4
100107
101- # Close when done.
102- db.close()
108+ # db is automatically closed when leaving the with statement.
103109
104110
105111.. seealso ::
0 commit comments