UUID7Generator#

class scikitplot.corpus.UUID7Generator(*, clock_ns=None, random_bytes=None)[source]#

Monotonic generator of RFC 9562 UUID version 7 identifiers.

Parameters:
clock_nscallable, optional

Returns the current Unix time in nanoseconds. Default time.time_ns. Injectable so that tests can step the clock.

random_bytescallable, optional

random_bytes(n) -> bytes returning n unpredictable bytes. Default os.urandom, the operating system’s CSPRNG (RFC 9562, section 6.9).

Parameters:
  • clock_ns (Callable[[], int] | None)

  • random_bytes (Callable[[int], bytes] | None)

Notes

User. Call the instance to get a uuid.UUID. One process needs one generator: the module-level uuid7 is that instance.

Developer. Thread-safe: the clock read, the counter step and the record of the result happen under one lock. Fork-safe for every instance, not only the module’s: each call compares os.getpid with the process that last used the instance and, in a forked child, calls reset before taking the lock. A lock held by another thread at the fork stays held in the child, and the child must not continue the parent’s counter (RFC 9562, section 6.9: reseed on fork).

Examples

>>> ticks = iter([5_000_000, 5_000_000, 1_000_000])
>>> make = UUID7Generator(clock_ns=lambda: next(ticks))
>>> a, b, c = make(), make(), make()
>>> a < b < c  # same millisecond, then a clock step backwards
True
>>> {uuid7_unix_ms(u) for u in (a, b, c)}
{5}
__call__()[source]#

Return the next identifier.

Returns:
uuid.UUID

Version 7, RFC 9562 variant, greater than every identifier this generator returned before.

Raises:
OverflowError

If the timestamp no longer fits 48 bits (the year 10889), or the clock reads before the Unix epoch.

ValueError

If random_bytes returns the wrong number of bytes.

TypeError

If random_bytes returns something other than bytes.

Return type:

UUID

reset()[source]#

Forget the sequence, so the next identifier starts a new one.

Notes

Replaces the lock instead of acquiring it: called in a forked child, where another thread of the parent may have held it at the fork.

Return type:

None