Initialize a new ObjectId. An ObjectId is a 12-byte unique identifier consisting of: - a 4-byte value representing the seconds since the Unix epoch, - a 5-byte random value, - a 3-byte counter, starting with a random value. By default, ``ObjectId()``
(self, oid: Optional[Union[str, ObjectId, bytes]] = None)
| 60 | _type_marker = 7 |
| 61 | |
| 62 | def __init__(self, oid: Optional[Union[str, ObjectId, bytes]] = None) -> None: |
| 63 | """Initialize a new ObjectId. |
| 64 | |
| 65 | An ObjectId is a 12-byte unique identifier consisting of: |
| 66 | |
| 67 | - a 4-byte value representing the seconds since the Unix epoch, |
| 68 | - a 5-byte random value, |
| 69 | - a 3-byte counter, starting with a random value. |
| 70 | |
| 71 | By default, ``ObjectId()`` creates a new unique identifier. The |
| 72 | optional parameter `oid` can be an :class:`ObjectId`, or any 12 |
| 73 | :class:`bytes`. |
| 74 | |
| 75 | For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId |
| 76 | specification but they are acceptable input:: |
| 77 | |
| 78 | >>> ObjectId(b'foo-bar-quux') |
| 79 | ObjectId('666f6f2d6261722d71757578') |
| 80 | |
| 81 | `oid` can also be a :class:`str` of 24 hex digits:: |
| 82 | |
| 83 | >>> ObjectId('0123456789ab0123456789ab') |
| 84 | ObjectId('0123456789ab0123456789ab') |
| 85 | |
| 86 | Raises :class:`~bson.errors.InvalidId` if `oid` is not 12 bytes nor |
| 87 | 24 hex digits, or :class:`TypeError` if `oid` is not an accepted type. |
| 88 | |
| 89 | :param oid: a valid ObjectId. |
| 90 | |
| 91 | .. seealso:: The MongoDB documentation on `ObjectIds <http://dochub.mongodb.org/core/objectids>`_. |
| 92 | |
| 93 | .. versionchanged:: 3.8 |
| 94 | :class:`~bson.objectid.ObjectId` now implements the `ObjectID |
| 95 | specification version 0.2 |
| 96 | <https://github.com/mongodb/specifications/blob/master/source/ |
| 97 | objectid.rst>`_. |
| 98 | """ |
| 99 | if oid is None: |
| 100 | # Generate a new value for this ObjectId. |
| 101 | with ObjectId._inc_lock: |
| 102 | inc = ObjectId._inc |
| 103 | ObjectId._inc = (inc + 1) % (_MAX_COUNTER_VALUE + 1) |
| 104 | |
| 105 | # 4 bytes current time, 5 bytes random, 3 bytes inc. |
| 106 | self.__id = _PACK_INT_RANDOM(int(time.time()), ObjectId._random()) + _PACK_INT(inc)[1:4] |
| 107 | elif isinstance(oid, bytes) and len(oid) == 12: |
| 108 | self.__id = oid |
| 109 | elif isinstance(oid, str): |
| 110 | if len(oid) == 24: |
| 111 | try: |
| 112 | self.__id = bytes.fromhex(oid) |
| 113 | except (TypeError, ValueError): |
| 114 | _raise_invalid_id(oid) |
| 115 | else: |
| 116 | _raise_invalid_id(oid) |
| 117 | elif isinstance(oid, ObjectId): |
| 118 | self.__id = oid.binary |
| 119 | else: |
nothing calls this directly
no test coverage detected