import urandom def uuid4(): b = bytearray(urandom.getrandbits(8) for _ in range(16)) # Set version (4) -> bits 12-15 of time_hi_and_version b[6] = (b[6] & 0x0F) | 0x40 # Set variant (RFC 4122) b[8] = (b[8] & 0x3F) | 0x80 def to_hex(x): return '{:02x}'.format(x) return ( to_hex(b[0]) + to_hex(b[1]) + to_hex(b[2]) + to_hex(b[3]) + '-' + to_hex(b[4]) + to_hex(b[5]) + '-' + to_hex(b[6]) + to_hex(b[7]) + '-' + to_hex(b[8]) + to_hex(b[9]) + '-' + to_hex(b[10]) + to_hex(b[11]) + to_hex(b[12]) + to_hex(b[13]) + to_hex(b[14]) + to_hex(b[15]) )