How to create a GUID/UUID in Python

Jonathon Watney picture Jonathon Watney · Feb 11, 2009 · Viewed 487.3k times · Source

How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?

Answer

stuartd picture stuartd · Feb 11, 2009

The uuid module, in Python 2.5 and up, provides RFC compliant UUID generation. See the module docs and the RFC for details. [source]

Docs:

Example (working on 2 and 3):

>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'