โ† Back to Blog

How to Generate a UUID in Python

2026-04-07 ยท 5 min read

Python uuid Standard Library Overview

Python has built-in the uuid module since version 2.5, requiring no additional packages. The module implements UUID versions 1, 3, 4, and 5 as defined in RFC 4122, providing the UUID class and several convenient generation functions. UUID objects can not only be converted to strings but also access individual fields (time_low, time_mid, clock_seq, etc.) and multiple representations like bytes, int, and hex. This makes Python's UUID operations very flexible, suitable for scenarios requiring precise control over UUID format.

Code Examples for Generating Each UUID Version

import uuid

# UUID v4๏ผˆๆœ€ๅธธ็”จ๏ผŒ้šๆœบ็”Ÿๆˆ๏ผ‰
id_v4 = uuid.uuid4()
print(id_v4)                    # UUID ๅฏน่ฑก
print(str(id_v4))               # ๅญ—็ฌฆไธฒ่กจ็คบ
print(id_v4.hex)                # ๆ— ่ฟžๅญ—็ฌฆ
print(id_v4.bytes)              # 16 ๅญ—่Š‚
print(id_v4.int)                # ๆ•ดๆ•ฐ

# UUID v1๏ผˆๆ—ถ้—ดๆˆณ + MAC ๅœฐๅ€๏ผ‰
id_v1 = uuid.uuid1()
print(id_v1)
print(id_v1.time)               # ๆ—ถ้—ดๆˆณๅญ—ๆฎต
print(id_v1.node)               # ่Š‚็‚น๏ผˆMAC๏ผ‰ๅญ—ๆฎต

# UUID v3๏ผˆMD5 ๅ“ˆๅธŒ๏ผŒ็กฎๅฎšๆ€ง๏ผ‰
id_v3 = uuid.uuid3(uuid.NAMESPACE_URL, 'https://example.com')
print(id_v3)

# UUID v5๏ผˆSHA-1 ๅ“ˆๅธŒ๏ผŒ็กฎๅฎšๆ€ง๏ผ‰
id_v5 = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
print(id_v5)

# ๆ ‡ๅ‡†ๅ‘ฝๅ็ฉบ้—ด
print(uuid.NAMESPACE_DNS)   # 6ba7b810-9dad-11d1-80b4-00c04fd430c8
print(uuid.NAMESPACE_URL)   # 6ba7b811-9dad-11d1-80b4-00c04fd430c8
print(uuid.NAMESPACE_OID)   # 6ba7b812-9dad-11d1-80b4-00c04fd430c8
print(uuid.NAMESPACE_X500)  # 6ba7b814-9dad-11d1-80b4-00c04fd430c8

Formatting UUID Output

import uuid

uid = uuid.uuid4()

# ไธๅŒๆ ผๅผ่พ“ๅ‡บ
print(str(uid))               # ๆ ‡ๅ‡†ๆ ผๅผ๏ผšxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
print(uid.hex)                # ๆ— ่ฟžๅญ—็ฌฆ๏ผšxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
print(str(uid).upper())       # ๅคงๅ†™ๆ ผๅผ
print(str(uid).replace('-', ''))  # ็งป้™ค่ฟžๅญ—็ฌฆ

# ่งฃๆž UUID ๅญ—็ฌฆไธฒ
parsed = uuid.UUID('550e8400-e29b-41d4-a716-446655440000')
parsed_no_dash = uuid.UUID('550e8400e29b41d4a716446655440000')  # ๆ— ่ฟžๅญ—็ฌฆไนŸๅฏไปฅ
parsed_braces = uuid.UUID('{550e8400-e29b-41d4-a716-446655440000}')  # ่Šฑๆ‹ฌๅท

# ๆŸฅ็œ‹็‰ˆๆœฌๅ’Œๅ˜ไฝ“
print(parsed.version)   # 4
print(parsed.variant)   # UUID ๅ˜ไฝ“ๆ ‡่ฏ†

# ๆ‰น้‡็”Ÿๆˆ
uuids = [str(uuid.uuid4()) for _ in range(10)]

Using UUID Primary Keys in Django

Django natively supports UUID as model primary keys using models.UUIDField. This is the recommended approach in Django for avoiding auto-increment primary keys and improving security. UUID primary keys do not expose the total count and order of database records, making them suitable for resource IDs in public-facing APIs.

# Django ๆจกๅž‹็คบไพ‹
import uuid
from django.db import models

class Article(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,  # ๆณจๆ„๏ผšไผ ๅ‡ฝๆ•ฐๅผ•็”จ่€Œ้ž่ฐƒ็”จ็ป“ๆžœ
        editable=False
    )
    title = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

# ไฝฟ็”จ
article = Article(title='Hello World')
article.save()
print(article.id)       # UUID ๅฏน่ฑก
print(str(article.id))  # ๅญ—็ฌฆไธฒ

Using UUID with SQLAlchemy

# SQLAlchemy ็คบไพ‹
import uuid
from sqlalchemy import Column, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import DeclarativeBase

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = 'users'

    # PostgreSQL ๅŽŸ็”Ÿ UUID ็ฑปๅž‹
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)

    # ๆˆ–ไฝฟ็”จ String ๅ…ผๅฎนๆ‰€ๆœ‰ๆ•ฐๆฎๅบ“
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))

UUID Type Annotations in FastAPI

# FastAPI + Pydantic ็คบไพ‹
from uuid import UUID, uuid4
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    id: UUID = None
    name: str

    def __init__(self, **data):
        if 'id' not in data:
            data['id'] = uuid4()
        super().__init__(**data)

@app.get('/items/{item_id}')
async def get_item(item_id: UUID):
    # FastAPI ่‡ชๅŠจ้ชŒ่ฏ item_id ๆ˜ฏๅฆๆ˜ฏๅˆๆณ• UUID
    return {'id': str(item_id)}

@app.post('/items')
async def create_item(item: Item):
    return item

Validating UUID Strings

import uuid

def is_valid_uuid(uuid_string: str) -> bool:
    """้ชŒ่ฏๅญ—็ฌฆไธฒๆ˜ฏๅฆๆ˜ฏๅˆๆณ•็š„ UUID"""
    try:
        uuid.UUID(uuid_string)
        return True
    except ValueError:
        return False

def is_valid_uuid_v4(uuid_string: str) -> bool:
    """้ชŒ่ฏๅญ—็ฌฆไธฒๆ˜ฏๅฆๆ˜ฏๅˆๆณ•็š„ UUID v4"""
    try:
        u = uuid.UUID(uuid_string)
        return u.version == 4
    except ValueError:
        return False

# ๆต‹่ฏ•
print(is_valid_uuid('550e8400-e29b-41d4-a716-446655440000'))  # True
print(is_valid_uuid('not-a-uuid'))  # False
print(is_valid_uuid_v4('550e8400-e29b-41d4-a716-446655440000'))  # False (v1)
print(is_valid_uuid_v4(str(uuid.uuid4())))  # True

Try the free tool now

Use Free Tool โ†’