@@ -100,7 +100,8 @@ The :meth:`!setdefault` method requires two arguments.
100100
101101Key and values are always stored as :class: `bytes `. This means that when
102102strings are used they are implicitly converted to the default encoding before
103- being stored.
103+ being stored. For detailed information about accepted types, see
104+ :ref: `dbm-key-value-types `.
104105
105106These objects also support being used in a :keyword: `with ` statement, which
106107will automatically close them when done.
@@ -121,6 +122,48 @@ will automatically close them when done.
121122 :meth: `!clear ` methods are now available for all :mod: `dbm ` backends.
122123
123124
125+ .. _dbm-key-value-types :
126+
127+ Key and Value Types
128+ -------------------
129+
130+ The accepted types for keys and values vary by backend:
131+
132+ **Keys: **
133+
134+ * **All backends **: Accept :class: `str ` and :class: `bytes ` objects
135+ * **String keys ** are automatically converted to bytes using the default
136+ encoding
137+ * **Bytes keys ** are stored as-is
138+
139+ **Values: **
140+
141+ * **Traditional backends ** (``dbm.gnu ``, ``dbm.ndbm ``, ``dbm.dumb ``): Only
142+ accept :class: `str ` and :class: `bytes ` objects
143+ * **SQLite backend ** (``dbm.sqlite3 ``): Accepts any object that can be
144+ converted to bytes:
145+
146+ * **Accepted **: :class: `str `, :class: `bytes `, :class: `int `,
147+ :class: `float `, :class: `bool `
148+ * **Rejected **: :class: `None `, :class: `list `, :class: `dict `,
149+ :class: `tuple `, custom objects
150+
151+ **Storage Format: **
152+
153+ All keys and values are stored as :class: `bytes ` objects in the database.
154+ When retrieving, you'll always get bytes back, regardless of the original
155+ type stored.
156+
157+ **Type Conversion Examples: **
158+
159+ * ``db['key'] = 'string' `` stored as ``b'string' ``
160+ * ``db['key'] = 42 `` stored as ``b'42' `` (sqlite3 only)
161+ * ``db['key'] = 3.14 `` stored as ``b'3.14' `` (sqlite3 only)
162+ * ``db['key'] = True `` stored as ``b'True' `` (sqlite3 only)
163+ * ``db['key'] = None `` fails on all backends
164+ * ``db['key'] = [1, 2, 3] `` fails on all backends
165+
166+
124167The following example records some hostnames and a corresponding title, and
125168then prints out the contents of the database::
126169
@@ -142,8 +185,9 @@ then prints out the contents of the database::
142185 # Often-used methods of the dict interface work too.
143186 print(db.get('python.org', b'not present'))
144187
145- # Storing a non-string key or value will raise an exception (most
146- # likely a TypeError).
188+ # Storing a non-string key or value behavior depends on the backend:
189+ # - Traditional backends (ndbm, gnu, dumb) will raise a TypeError
190+ # - The sqlite3 backend accepts it and converts to bytes
147191 db['www.yahoo.com'] = 4
148192
149193 # db is automatically closed when leaving the with statement.
0 commit comments