Skip to content

Commit 3c0e0f5

Browse files
authored
Use binary_type in MongoDBStore.__getitem__ for Python 2 only (#401)
* Drop binary_type cast in MongoDBStore.__getitem__ * Coerce PyMongo values to `binary_type` on Python 2 On both Python 2 and Python 3, PyMongo converts `binary_type` (i.e. `bytes`) to BSON type 5 (Binary data) with subtype 0 to store in the MongoDB instance. When reading that data back out, PyMongo handles BSON type 5 (Binary data) with subtype 0 differently depending on the Python version. On Python 2, it creates a `bson.Binary` instance with the data. Normally we would coerce this to a `bytes` object using `ensure_bytes`. However that fails as `bson.Binary` is a subclass of `bytes`. So instead we explicitly force it to `bytes` (i.e. `binary_type`). On Python 3, PyMongo automatically converts the data to `bytes`. Thus we don't need to do anything there. ref: http://api.mongodb.com/python/current/python3.html#id3 ref: http://api.mongodb.com/python/current/api/bson/binary.html#bson.binary.Binary
1 parent b76b282 commit 3c0e0f5

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

zarr/storage.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2147,7 +2147,15 @@ def __getitem__(self, key):
21472147
if doc is None:
21482148
raise KeyError(key)
21492149
else:
2150-
return binary_type(doc[self._value])
2150+
value = doc[self._value]
2151+
2152+
# Coerce `bson.Binary` to `bytes` type on Python 2.
2153+
# PyMongo handles this conversion for us on Python 3.
2154+
# ref: http://api.mongodb.com/python/current/python3.html#id3
2155+
if PY2: # pragma: py3 no cover
2156+
value = binary_type(value)
2157+
2158+
return value
21512159

21522160
def __setitem__(self, key, value):
21532161
value = ensure_bytes(value)

0 commit comments

Comments
 (0)