Is uuid.uuid4() safe to use on Windows with multiprocessing?

Viewed 144

I am running a multi-process program in Python (Python 3.10)

I am using the uuid library to create a random uuid (uuid.uuid4()) The uuid documentation provided a 'is_safe' method that suppose to tell the developer if the uuid created is safe to use in a multi-process environment. see link

When running on Windows the 'is_safe' method returns 'SafeUUID.unknown' Does anyone know if Windows generates safe UUID?

1 Answers

I have the exact same question as you, and I don't know the answer.

I had some code like this

rand_id = uuid.uuid4()
assert rand_id.is_safe == uuid.SafeUUID.safe, f"uuid.uuid4() returned a UUID object with is_safe = {rand_id.is_safe} != uuid.SafeUUID.safe"

which was failing that assert because uuid4 returns SafeUUID.unknown instead.

What I can add is that this behavior seems to be hard wired into uuid4. Here is what its implementation looks like (in the Python 3.8 used in my current venv):

def uuid4():
    """Generate a random UUID."""
    return UUID(bytes=os.urandom(16), version=4)

The key point is that by failing to supply the is_safe arg in that UUID constructor call, its default value of SafeUUID.unknown will be used.

This explains why we see the behavior that we do on Windows (and presumably every other OS too).

If someone has insight into why uuid4 is coded the way it is, if it changes in later versions of Python, etc I would love to know.

Related