diff --git a/Lib/uuid.py b/Lib/uuid.py index 4d4f06cfc9ebbe..83848da943bf46 100644 --- a/Lib/uuid.py +++ b/Lib/uuid.py @@ -657,6 +657,7 @@ def getnode(): _last_timestamp = None +_last_clock_seq = None def uuid1(node=None, clock_seq=None): """Generate a UUID from a host ID, sequence number, and the current time. @@ -674,15 +675,22 @@ def uuid1(node=None, clock_seq=None): is_safe = SafeUUID.unknown return UUID(bytes=uuid_time, is_safe=is_safe) - global _last_timestamp + global _last_timestamp, _last_clock_seq import time nanoseconds = time.time_ns() # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = nanoseconds // 100 + 0x01b21dd213814000 if _last_timestamp is not None and timestamp <= _last_timestamp: - timestamp = _last_timestamp + 1 + # if there is a previous clock sequence, then increment + # otherwise, the clock sequence will be regenerated + if _last_clock_seq is not None: + clock_seq = _last_clock_seq + 1 + else: + import random + clock_seq = random.getrandbits(14) # regen _last_timestamp = timestamp + _last_clock_seq = clock_seq if clock_seq is None: import random clock_seq = random.getrandbits(14) # instead of stable storage diff --git a/Misc/NEWS.d/next/Library/2024-09-26-10-49-38.gh-issue-88786.egE0mj.rst b/Misc/NEWS.d/next/Library/2024-09-26-10-49-38.gh-issue-88786.egE0mj.rst new file mode 100644 index 00000000000000..2eb1a9c4b88f80 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-26-10-49-38.gh-issue-88786.egE0mj.rst @@ -0,0 +1 @@ +Update :func:`uuid.uuid1` in :mod:`uuid` to meet RFC4122.