Open In App

Generating Random id’s using UUID in Python

We had discussed the ways to generate unique id’s in Python without using any python inbuilt library in Generating random Id’s in Python

In this article we would be using inbuilt functions to generate them.



UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. It provides the uniqueness as it generates ids on the basis of time, Computer hardware (MAC etc.).

Advantages of UUID :



Method 1 : Using uuid1()

uuid1() is defined in UUID library and helps to generate the random id using MAC address and time component.




# Python3 code to generate the
# random id using uuid1()
  
import uuid
  
# Printing random id using uuid1()
print ("The random id using uuid1() is : ",end="")
print (uuid.uuid1())

Output :

The random id using uuid1() is : 67460e74-02e3-11e8-b443-00163e990bdb

Representations of uuid1()

Components of uuid1()

Fields of uuid1()




# Python3 code to demonstrate
# components, representations 
# and variants of uuid1()
  
import uuid
  
id = uuid.uuid1()
  
# Representations of uuid1()
print ("The Representations of uuid1() are : ")
print ("byte Representation : ",end="")
print (repr(id.bytes))
  
print ("int Representation : ",end="")
print (id.int)
  
print ("hex Representation : ",end="")
print (id.hex)
  
print("\n")
  
# Components of uuid1()
print ("The Components of uuid1() are : ")
print ("Version  : ",end="")
print (id.version)
  
print ("Variant : ",end="")
print (id.variant)
  
print("\n")
  
# Fields of uuid1()
print ("The Fields of uuid1() are : ")
print ("Fields  : ",end="")
print (id.fields)
  
print("\n")
  
# Time Component of uuid1()
print ("The time Component of uuid1() is : ")
print ("Time component  : ",end="")
print (id.node)

Output :

The Representations of uuid1() are : 
byte Representation : b'k\x10\xa1n\x02\xe7\x11\xe8\xaeY\x00\x16>\x99\x0b\xdb'
int Representation : 142313746482664936587190810281013480411
hex Representation : 6b10a16e02e711e8ae5900163e990bdb


The Components of uuid1() are : 
Version  : 1
Variant : specified in RFC 4122


The Fields of uuid1() are : 
Fields  : (1796252014, 743, 4584, 174, 89, 95539497947)


The time Component of uuid1() is : 
Time component  : 95539497947

Drawback :
This way includes the used of MAC address of computer, and hence can compromise the privacy, even though it provides uniquenes.

Method 2 : Using uuid4()
This function guarantees the random no. and doesn’t compromise with privacy.




# Python3 code to generate
# id using uuid4()
  
import uuid
  
id = uuid.uuid4()
  
# Id generated using uuid4()
print ("The id generated using uuid4() : ",end="")
print (id)

Output :

The id generated using uuid4() : fbd204a7-318e-4dd3-86e0-e6d524fc3f98

Article Tags :