How to create a GUID/UUID in Python


Question

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?

1
582
1/13/2018 2:40:01 PM

Accepted Answer

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'
641
8/31/2018 2:09:49 PM

If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon