Skip to content

Commit c0ef434

Browse files
committed
gh-158217: Fix dbm.dumb bytearray keys
1 parent ee1bbf0 commit c0ef434

3 files changed

Lines changed: 20 additions & 1 deletion

File tree

‎Lib/dbm/dumb.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ def _verify_open(self):
144144
def __getitem__(self, key):
145145
if isinstance(key, str):
146146
key = key.encode('utf-8')
147+
elif isinstance(key, bytearray):
148+
key = bytes(key)
147149
self._verify_open()
148150
pos, siz = self._index[key] # may raise KeyError
149151
with _io.open(self._datfile, 'rb') as f:
@@ -189,7 +191,9 @@ def __setitem__(self, key, val):
189191
raise error('The database is opened for reading only')
190192
if isinstance(key, str):
191193
key = key.encode('utf-8')
192-
elif not isinstance(key, (bytes, bytearray)):
194+
elif isinstance(key, bytearray):
195+
key = bytes(key)
196+
elif not isinstance(key, bytes):
193197
raise TypeError("keys must be bytes or strings")
194198
if isinstance(val, str):
195199
val = val.encode('utf-8')
@@ -226,6 +230,8 @@ def __delitem__(self, key):
226230
raise error('The database is opened for reading only')
227231
if isinstance(key, str):
228232
key = key.encode('utf-8')
233+
elif isinstance(key, bytearray):
234+
key = bytes(key)
229235
self._verify_open()
230236
self._modified = True
231237
# The blocks used by the associated value are lost.
@@ -249,6 +255,8 @@ def items(self):
249255
def __contains__(self, key):
250256
if isinstance(key, str):
251257
key = key.encode('utf-8')
258+
elif isinstance(key, bytearray):
259+
key = bytes(key)
252260
try:
253261
return key in self._index
254262
except TypeError:

‎Lib/test/test_dbm_dumb.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,15 @@ def test_dumbdbm_creation(self):
4141
f[key] = self._dict[key]
4242
self.read_helper(f)
4343

44+
def test_dumbdbm_bytearray_keys(self):
45+
# gh-158217: bytearray keys must not raise TypeError:
46+
with contextlib.closing(dumbdbm.open(_fname, 'c')) as f:
47+
f[bytearray(b'key')] = b'value'
48+
self.assertEqual(f[bytearray(b'key')], b'value')
49+
self.assertIn(bytearray(b'key'), f)
50+
del f[bytearray(b'key')]
51+
self.assertNotIn(bytearray(b'key'), f)
52+
4453
@unittest.skipUnless(hasattr(os, 'umask'), 'test needs os.umask()')
4554
@os_helper.skip_unless_working_chmod
4655
def test_dumbdbm_creation_mode(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :mod:`dbm.dumb` to accept ``bytearray`` keys, consistent with the
2+
other :mod:`dbm` backends. Patch by Tony Leung.

0 commit comments

Comments
 (0)