1

I need a function to generate/return a unique ID in a Python script, but I need it to satisfy a few requirements:

  • Must be different every run
  • Must be the same value within a single run, even if:
    • Multiple classes call it
    • Multiple threads (xdist) within one run call it
    • All existing references to it fall out of scope
  • If two instances of the script are running simultaneously, each instance gets its own ID.

I've looked at the uuid package, but it returns a different ID each time the methods are called. How can I have an ID be consistent throughout an entire run?

sprad
  • 313
  • 3
  • 10
  • You almost have the answer already: create the unique ID at the start of the run, store it in a local (to the instance) variable, and refer to that variable from then on. – Prune Apr 26 '18 at 21:44

1 Answers1

1

Just put the ID in a variable and use that everywhere.

If your program is large and you'd like an easier way for everything to access it, make a little module to store it in, say uniqid.py (or put it in some generic utility module):

import uuid

uniqid = str(uuid.uuid4())

Then whenever you need your ID just

from uniqid import uniqid

print(uniqid)

Modules are instantiated only once even if imported by multiple files.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • I tried this out, and it works when I run single-threaded. But when I turn on multiple threads with xdist, uniqid shows different values in different parts of the program. (in my case, the value differs between setup methods in conftest.py and within test cases) – sprad Apr 26 '18 at 22:04
  • Are you sure "xdist" uses threading, and not multiple processes? If it uses multiple processes, and doesn't fork() them from the same one or something, the module will get loaded separately for each one. This would correspond to the "two instances" case you mentioned. And if you still want those instances to get the same ID, at that point this becomes not a plain Python question, but a question about xdist. – Matti Virkkunen Apr 26 '18 at 22:10