Skip to content

Commit f4ec4be

Browse files
committed
Avoid encoding errors with pickle.loads PYTHON-355.
This works around issues caused by applications that use sys.setdefaultencoding to set an interpreter-wide encoding other than ascii or utf8. This is only an issue in python 2.x. In python 3.0 and 3.1 setdefaultencoding is a noop. It was completely removed in python 3.2.
1 parent 7df3540 commit f4ec4be

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

bson/objectid.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
import time
3333

3434
from bson.errors import InvalidId
35-
from bson.py3compat import (b, binary_type, text_type,
35+
from bson.py3compat import (PY3, b, binary_type, text_type,
3636
bytes_from_hex, string_types)
3737
from bson.tz_util import utc
3838

@@ -208,21 +208,18 @@ def __setstate__(self, value):
208208
"""explicit state set from pickling
209209
"""
210210
# Provide backwards compatability with OIDs
211-
# pickled with pymongo-1.9.
211+
# pickled with pymongo-1.9 or older.
212212
if isinstance(value, dict):
213-
try:
214-
# ObjectIds pickled in python 2.x used `str` for __id.
215-
# In python 3.x this has to be converted to `bytes`
216-
# by encoding latin-1.
217-
self.__id = value['_ObjectId__id'].encode('latin-1')
218-
except UnicodeDecodeError:
219-
self.__id = value['_ObjectId__id']
213+
oid = value["_ObjectId__id"]
220214
else:
221-
try:
222-
# See the previous comment about python 2/3 pickle issues.
223-
self.__id = value.encode('latin-1')
224-
except (UnicodeDecodeError, AttributeError):
225-
self.__id = value
215+
oid = value
216+
# ObjectIds pickled in python 2.x used `str` for __id.
217+
# In python 3.x this has to be converted to `bytes`
218+
# by encoding latin-1.
219+
if PY3 and isinstance(oid, text_type):
220+
self.__id = oid.encode('latin-1')
221+
else:
222+
self.__id = oid
226223

227224
def __str__(self):
228225
return binascii.hexlify(self.__id).decode()

0 commit comments

Comments
 (0)