[Python] Is it possible to generate unique ids based on monotonic clock in python?

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I need to implement fast generator of unique IDs in Python. And my idea is:

    from time import time


    def generate(prefix: str) -> str:
    return prefix + str(time.monotonic_ns())


    Where prefix is a random string generated once on process start.

    Since monotonic value is always increased, I can be sure that IDs inside a single process will be unique. And since prefix is supposed to be a unique value for a specific period of time, I can be sure that IDs between processes also will be unique.

    But I don't understand what is arbitrary starting point for monotonic clock in Python?

    Let's say that my service is running half year without restart. Is it possible that monotonic time will be reset or repeated for the period of time and I'll get the same value for an ID inside single process?

    Continue reading...

Compartilhe esta Página