|
32 | 32 | import time
|
33 | 33 |
|
34 | 34 | 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, |
36 | 36 | bytes_from_hex, string_types)
|
37 | 37 | from bson.tz_util import utc
|
38 | 38 |
|
@@ -208,21 +208,18 @@ def __setstate__(self, value):
|
208 | 208 | """explicit state set from pickling
|
209 | 209 | """
|
210 | 210 | # Provide backwards compatability with OIDs
|
211 |
| - # pickled with pymongo-1.9. |
| 211 | + # pickled with pymongo-1.9 or older. |
212 | 212 | 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"] |
220 | 214 | 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 |
226 | 223 |
|
227 | 224 | def __str__(self):
|
228 | 225 | return binascii.hexlify(self.__id).decode()
|
|
0 commit comments