Hi Pythonistas!
In the previous post we have learned about uuid module. Today we are dive into uuid4's internal working.
What's UUID4?
There are different versions of UUIDs. UUID4 is special because it's made entirely from random numbers (no timestamps, no MAC addresses). It's perfect when you just want something unique without worrying about sequence or predictability.
How Python Generates UUID4 Internally
When you run
import uuid
uuid.uuid4()
Here's what happens step-by-step:
Step 1 - Get Randomness
UUID4 starts by asking the computer for 16 completely random bytes from a secure source.
On Linux: /dev/urandom
On Windows: system cryptographic API
Think of it as picking 16 random lottery balls, each numbered from 0–255.
Step 2 - Stamp the Version
UUID4 must have a version number in it so we change a few bits in the 7th byte to say "Hey, I'm version 4".
Step 3 - Stamp the Variant
Another small part (in the 9th byte) is changed to say "I follow the official UUID rules" (RFC 4122).
Step 4 - Format It Nicely
The 16 bytes are then shown as hex numbers split into 5 groups with dashes.
Why It's (Practically) Unique
UUID4 gives you 2^122 possible values. That's 5316911983139663491615228241121378304 possibilities ,
so even generating billions of UUIDs for years won’t realistically cause a collision.
import uuid
u = uuid.uuid4()
print("UUID4:", u)
Output:
UUID4: 550e8400-e29b-41d4-a716-446655440000
Summary
UUID4 = Secure random bytes + fixed version & variant bits
Purpose: Avoid duplicates in distributed systems, databases, and APIs
Bonus: It’s fast and requires no coordination between machines