Python में UUID v4 जेनरेट करें — uuid.uuid4()

·Backend Developer·समीक्षकDmitri Volkov·प्रकाशित

मुफ़्त UUID v4 Generator को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।

UUID v4 Generator ऑनलाइन आज़माएं →

जब भी मुझे database row, API trace, या session token के लिए एक collision-resistant identifier चाहिए, तो जवाब है Python में UUID v4 जेनरेट करना — एक लाइन, zero dependencies: uuid.uuid4()। Python का बिल्ट-इन uuid मॉड्यूल क्रिप्टोग्राफ़िक रूप से सुरक्षित randomness के लिए os.urandom() का उपयोग करता है। कोड लिखे बिना एक त्वरित UUID के लिए, ऑनलाइन UUID v4 generator तुरंत काम करता है। यह गाइड UUID ऑब्जेक्ट के एट्रिब्यूट, bulk generation, JSON serialization, database storage, validation, uuid-utils (~10× तेज़ Rust-backed drop-in), और चार सबसे सामान्य गलतियाँ — सब Python 3.8+ के साथ — cover करती है।

मुख्य बिंदु
  • uuid.uuid4() Python की stdlib में बिल्ट-इन है — बस import uuid काफ़ी है, कोई pip install नहीं।
  • रिटर्न वैल्यू एक uuid.UUID ऑब्जेक्ट है, string नहीं — अपनी storage layer के अनुसार str(), .hex, या .bytes से प्रतिनिधित्व चुनें।
  • UUID v4, os.urandom() से 122 random bits का उपयोग करता है — क्रिप्टोग्राफ़िक रूप से सुरक्षित, MAC address या timestamp उजागर नहीं होता।
  • उच्च-throughput सेवाओं के लिए, pip install uuid-utils एक drop-in replacement है जो Rust द्वारा संचालित ~10x तेज़ है।
  • dataclass या Pydantic model में uuid.uuid4 (बिना parentheses) को सीधे default argument के रूप में कभी न दें — यह सभी instances में एक ही UUID share करेगा।

UUID v4 क्या है?

UUID (Universally Unique Identifier) एक 128-बिट लेबल है जिसे 32 hexadecimal अंकों में फ़ॉर्मेट किया गया है, hyphens द्वारा पाँच समूहों में विभाजित: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx। Version 4 सबसे व्यापक रूप से उपयोग किया जाने वाला variant है: उन 128 bits में से 122 randomly जेनरेट होते हैं, और शेष 6 bits version (4) और variant (RFC 4122) encode करते हैं। कोई timestamp नहीं और कोई host identifier नहीं — identifier पूरी तरह opaque और privacy-safe है। दो स्वतंत्र रूप से जेनरेट किए गए v4 UUIDs के टकराने की संभावना इतनी कम है कि व्यावहारिक रूप से यह कभी नहीं होता, यहाँ तक कि distributed systems में भी जहाँ प्रति सेकंड लाखों IDs जेनरेट होते हैं।

Before · Python
After · Python
event_id = "evt-" + str(random.randint(100000, 999999))  # fragile, not unique
event_id = str(uuid.uuid4())  # 3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e

uuid.uuid4() — Python में UUID v4 जेनरेट करने का मानक तरीका

uuid मॉड्यूल Python की standard library का हिस्सा है। uuid.uuid4() कॉल करने पर एक uuid.UUID ऑब्जेक्ट मिलता है जिसमें विभिन्न प्रतिनिधित्वों के लिए एट्रिब्यूट का पूरा सेट होता है। str() से string में बदलने पर canonical hyphenated format मिलता है जो APIs, databases, और HTTP headers को चाहिए।

Python 3.8+ — न्यूनतम उदाहरण
import uuid

# UUID v4 जेनरेट करें
request_id = uuid.uuid4()

print(request_id)           # 3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e
print(type(request_id))     # <class 'uuid.UUID'>
print(request_id.version)   # 4

# JSON / HTTP headers के लिए string में बदलें
print(str(request_id))      # "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e"
print(request_id.hex)       # "3b1f8a9d2c4e4f6a8b0d5e7c9f1a3d2e" (बिना dashes)
print(request_id.bytes)     # b';...' (16 raw bytes)

एक सामान्य real-world pattern हर outbound API request में UUID जोड़ना है ताकि आप services में logs को correlate कर सकें। यहाँ एक minimal requests session wrapper है जो हर call में एक fresh UUID inject करता है:

Python 3.8+ — प्रति-request trace ID
import uuid
import requests

def call_api(endpoint: str, payload: dict) -> dict:
    trace_id = str(uuid.uuid4())
    headers = {
        "X-Request-ID": trace_id,
        "Content-Type": "application/json",
    }
    response = requests.post(endpoint, json=payload, headers=headers, timeout=10)
    response.raise_for_status()
    return {"trace_id": trace_id, "data": response.json()}

# result["trace_id"] से सभी service logs में उस exact request को grep कर सकते हैं
result = call_api("https://api.example.com/v1/orders", {"product_id": "prod_7x2k", "qty": 3})
print(result["trace_id"])  # जैसे "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e"

UUIDs bulk में जेनरेट करते समय — उदाहरण के लिए, database rows का एक batch pre-populate करने के लिए — list comprehension idiomatic और readable है:

Python 3.8+ — bulk generation
import uuid

# 1000 telemetry events के लिए IDs पहले से जेनरेट करें
event_ids = [str(uuid.uuid4()) for _ in range(1000)]
print(f"Generated {len(event_ids)} unique IDs")
print(event_ids[0])   # जैसे "a1c2e3f4-..."
print(event_ids[-1])  # हर बार अलग वैल्यू

कोई भी कोड चलाए बिना quick UUID चाहिए? एक click में fresh वैल्यू copy करने के लिए ऑनलाइन UUID v4 generator का उपयोग करें, या एक साथ सैकड़ों जेनरेट करें — test databases seed करने या fixture files populate करने के लिए उपयोगी।

नोट:uuid.uuid4() आंतरिक रूप से os.urandom(16) कॉल करता है, फिर byte 8 के bits 6–7 को 10 (variant) और byte 6 के bits 12–15 को 0100 (version 4) सेट करता है। शेष 122 bits random हैं। इसीलिए version पर तब तक भरोसा नहीं किया जा सकता जब तक आप uuid.UUID() से parse न करें।

UUID ऑब्जेक्ट के एट्रिब्यूट और प्रतिनिधित्व

uuid.UUID ऑब्जेक्ट उसी 128-बिट वैल्यू के कई प्रतिनिधित्व expose करता है। अपनी storage layer के लिए सही एक चुनने से silent data corruption और बर्बाद bytes से बचा जा सकता है।

एट्रिब्यूट / मेथड
प्रकार
विवरण
uuid.UUID(hex=...)
UUID
किसी मौजूदा UUID को hex स्ट्रिंग से पार्स करें — dashes के साथ या बिना dashes के।
.hex
str
32 अक्षरों की lowercase hex स्ट्रिंग जिसमें hyphens नहीं हैं — कॉम्पैक्ट स्टोरेज फॉर्मेट।
.int
int
UUID का 128-बिट integer प्रतिनिधित्व — arithmetic और sorting के लिए उपयोगी।
.bytes
bytes
16-byte big-endian बाइनरी प्रतिनिधित्व — सबसे कुशल स्टोरेज साइज़।
.bytes_le
bytes
16-byte little-endian बाइनरी — Microsoft GUID byte क्रम से मेल खाता है।
.fields
tuple
UUID फ़ील्ड्स का छह-तत्व टपल: (time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node)।
.version
int | None
UUID वर्शन संख्या (1–5, या गैर-मानक UUIDs के लिए None)।
.variant
str
UUID variant स्ट्रिंग — मानक UUIDs के लिए "specified in RFC 4122"।
str(uuid_obj)
str
चार hyphens के साथ canonical 36-अक्षर स्ट्रिंग: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx।
Python 3.8+ — सभी प्रतिनिधित्व
import uuid

u = uuid.uuid4()

print(str(u))         # "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e"  (36 chars)
print(u.hex)          # "3b1f8a9d2c4e4f6a8b0d5e7c9f1a3d2e"      (32 chars, बिना dashes)
print(u.bytes)        # b';Š...'                       (16 bytes, big-endian)
print(u.bytes_le)     # b'Š...'                       (16 bytes, little-endian)
print(u.int)          # 78823... (128-bit integer)
print(u.version)      # 4
print(u.variant)      # 'specified in RFC 4122'

# Round-trip: string से फिर से बनाएं
reconstructed = uuid.UUID("3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e")
print(reconstructed == u)  # True (अगर u वही वैल्यू थी)

psycopg2 या asyncpg के साथ PostgreSQL के लिए, UUID ऑब्जेक्ट सीधे पास करें — driver इसे native uuid column type में map करता है। SQLite के लिए, जिसमें native UUID type नहीं है, str(u) (TEXT) या u.bytes (BLOB, string के 36 bytes की जगह 16 bytes) का उपयोग करें। बड़े पैमाने पर storage efficiency के लिए, .bytes canonical string से 55% छोटा है।

Python में UUID v4 स्ट्रिंग्स को Validate और Parse करना

जब भी कोई UUID user input, URL path parameter, या upstream API से आए, तो database key के रूप में उपयोग करने से पहले उसे validate करना चाहिए। Idiomatic approach है uuid.UUID() से construction का प्रयास करना और ValueError catch करना। आप .version जाँच कर यह भी enforce कर सकते हैं कि आने वाली वैल्यू specifically version 4 है।

Python 3.8+ — validation helper
import uuid

def parse_uuid4(raw: str) -> uuid.UUID:
    """
    UUID v4 स्ट्रिंग को parse और validate करें।
    अमान्य format या गलत version के लिए ValueError उठाता है।
    """
    try:
        u = uuid.UUID(raw)
    except ValueError as exc:
        raise ValueError(f"Invalid UUID format: {raw!r}") from exc

    if u.version != 4:
        raise ValueError(f"Expected UUID v4, got v{u.version}: {raw!r}")

    return u

# FastAPI / Flask route handler में उपयोग
def get_order(order_id: str):
    try:
        uid = parse_uuid4(order_id)
    except ValueError as exc:
        return {"error": str(exc)}, 400

    # अब uid को DB query में safely उपयोग कर सकते हैं
    return {"order_id": str(uid), "status": "processing"}
नोट:uuid.UUID() hyphens के साथ और बिना hyphens के दोनों स्ट्रिंग स्वीकार करता है, और urn:uuid: prefix भी स्वीकार करता है। तो "3b1f8a9d2c4e4f6a8b0d5e7c9f1a3d2e" (बिना dashes) और "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e" दोनों एक ही ऑब्जेक्ट में parse होते हैं।

JSON Payloads और API Responses में UUID v4

JSON standard में कोई UUID type नहीं है — JSON में UUID हमेशा एक string होता है। इसका मतलब है किjson.dumps() को पास करने से पहले uuid.UUID ऑब्जेक्ट को string में बदलना होगा। सबसे साफ़ approach एक custom JSONEncoder subclass है ताकि आपको अपने codebase में str() calls बिखेरनी न पड़ें।

Python 3.8+ — UUID के लिए custom JSONEncoder
import json
import uuid
from datetime import datetime

class ApiEncoder(json.JSONEncoder):
    """JSON responses में UUID और datetime ऑब्जेक्ट serialize करें।"""
    def default(self, obj):
        if isinstance(obj, uuid.UUID):
            return str(obj)
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)

# nested UUIDs के साथ realistic API response
api_response = {
    "request_id": uuid.uuid4(),
    "created_at": datetime(2026, 3, 14, 9, 41, 0),
    "order": {
        "id": uuid.uuid4(),
        "customer_id": uuid.uuid4(),
        "items": [
            {"product_id": uuid.uuid4(), "sku": "NVX-9000", "qty": 2},
        ],
    },
}

print(json.dumps(api_response, indent=2, cls=ApiEncoder))
# {
#   "request_id": "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e",
#   "created_at": "2026-03-14T09:41:00",
#   "order": {
#     "id": "a1c2e3f4-...",
#     ...
#   }
# }

एक बार के serialization call के लिए, subclassing की जगह default= hook सरल है:

Python 3.8+ — default= hook (एक बार के लिए)
import json, uuid

event_id = uuid.uuid4()
payload = {"event_id": event_id, "action": "checkout"}

# एक callable पास करें; केवल उन types के लिए कॉल होता है जिन्हें json handle नहीं कर सकता
json_str = json.dumps(payload, default=str)
print(json_str)  # {"event_id": "3b1f8a9d-...", "action": "checkout"}

किसी external API से response receive करते समय, UUID strings को वापस ऑब्जेक्ट में parse करें ताकि आपके code को पूरा attribute set और type safety मिले:

Python 3.8+ — API response से UUID parse करना
import json
import uuid
import requests

def fetch_shipment(shipment_id: str) -> dict:
    """एक shipment fetch करें और typed UUID fields के साथ return करें।"""
    response = requests.get(
        f"https://api.logistics.example.com/v2/shipments/{shipment_id}",
        headers={"Accept": "application/json"},
        timeout=10,
    )
    response.raise_for_status()
    data = response.json()

    # UUID fields को वापस uuid.UUID ऑब्जेक्ट में parse करें
    try:
        data["id"] = uuid.UUID(data["id"])
        data["carrier_id"] = uuid.UUID(data["carrier_id"])
    except (KeyError, ValueError) as exc:
        raise RuntimeError(f"Malformed shipment response: {exc}") from exc

    return data

disk पर किसी JSON file में UUID fields update करने के लिए — उदाहरण के लिए, किसी config या seed file में correlation ID rotate करने के लिए — read करें, mutate करें, और atomically वापस write करें:

Python 3.8+ — JSON file पढ़ना, update करना, और लिखना
import json, uuid

def rotate_correlation_id(path: str) -> str:
    """JSON file में 'correlation_id' को बदलें या जोड़ें। नया UUID return करता है।"""
    try:
        with open(path) as f:
            data = json.load(f)
    except FileNotFoundError:
        data = {}
    except json.JSONDecodeError as exc:
        raise ValueError(f"Invalid JSON in {path!r}: {exc}") from exc

    new_id = str(uuid.uuid4())
    data["correlation_id"] = new_id

    with open(path, "w") as f:
        json.dump(data, f, indent=2)

    return new_id

अगर आप API response से UUID inspect करने के लिए हर बार script नहीं चलाना चाहते, तो इसे सीधे UUID Decoder में paste करें — यह बिना किसी code के version, variant, और सभी fields दिखाता है।

Python से Command Line पर UUID v4 जेनरेट करना

Python का uuid मॉड्यूल python -m json.tool जैसा standalone CLI subcommand expose नहीं करता, लेकिन एक one-liner वही काम करता है। ये shell scripts, CI pipelines, और जब भी REPL खोले बिना throwaway identifier चाहिए, तब उपयोगी हैं।

bash
# Single UUID v4
python3 -c "import uuid; print(uuid.uuid4())"
# 3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e

# No-dashes (hex) format — filenames और env vars के लिए उपयोगी
python3 -c "import uuid; print(uuid.uuid4().hex)"
# 3b1f8a9d2c4e4f6a8b0d5e7c9f1a3d2e

# batch seed script के लिए 5 UUIDs जेनरेट करें
python3 -c "import uuid; [print(uuid.uuid4()) for _ in range(5)]"

# shell variable में उपयोग
DEPLOY_ID=$(python3 -c "import uuid; print(uuid.uuid4())")
echo "Deploying with ID: $DEPLOY_ID"
नोट:macOS और अधिकांश Linux distributions पर, uuidgen (एक C utility) UUID v4 वैल्यू produce करता है और pure shell scripts के लिए तेज़ है। Python one-liner का उपयोग तब करें जब आप पहले से Python-centric environment में हों और चाहते हों कि UUIDs उसी तरह जेनरेट हों जैसे आपके application code में होते हैं।

uuid-utils के साथ उच्च-प्रदर्शन UUID v4

Standard library का uuid.uuid4() अधिकांश applications के लिए पर्याप्त तेज़ है — प्रति call कुछ microseconds पर यह प्रति सेकंड हज़ारों IDs आराम से handle करता है। अगर आप किसी high-throughput service के hot path पर UUIDs जेनरेट कर रहे हैं (bulk inserts, बड़े पैमाने पर per-event telemetry, या heavy load में request ID generation), uuid-utils एक drop-in replacement है जो Rust द्वारा backed है और stdlib की तुलना में लगभग 10x तेज़ benchmark करता है।

bash — install
pip install uuid-utils
Python 3.8+ — uuid-utils drop-in replacement
# uuid_utils stdlib uuid module का drop-in replacement है
import uuid_utils as uuid

# stdlib जैसा ही API
request_id = uuid.uuid4()
print(request_id)           # 3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e
print(str(request_id))      # canonical string
print(request_id.hex)       # no-dashes hex
print(request_id.version)   # 4

# v7 भी support करता है (time-ordered, DB primary keys के लिए बढ़िया)
time_ordered_id = uuid.uuid7()
print(time_ordered_id)      # current-timestamp prefix से शुरू होता है
चेतावनी:uuid-utils का default mode अपना UUID ऑब्जेक्ट type return करता है, जो अधिकांश cases में stdlib के साथ compatible है। अगर आपको standard library से strict isinstance(u, uuid.UUID) checks चाहिए, तो compat mode का उपयोग करें: import uuid_utils.compat as uuid। Compat mode default से थोड़ा धीमा है लेकिन फिर भी stdlib से तेज़ है।

Dataclasses और Pydantic Models में UUID v4

Python dataclasses और Pydantic models दोनों UUID fields को natively support करते हैं। UUID को auto-generated default के रूप में उपयोग करते समय मुख्य pattern यह है कि function reference पास करें, call result नहीं — अन्यथा हर instance एक ही UUID share करेगा।

Python 3.10+ — UUID default के साथ dataclass
from dataclasses import dataclass, field
import uuid

@dataclass
class WorkerJob:
    job_id: uuid.UUID = field(default_factory=uuid.uuid4)
    worker_id: str = "worker-01"
    payload: dict = field(default_factory=dict)

job1 = WorkerJob(payload={"task": "resize_image", "src": "uploads/img_4932.png"})
job2 = WorkerJob(payload={"task": "send_email",   "to":  "ops@example.com"})

print(job1.job_id)  # प्रति instance अनन्य
print(job2.job_id)  # job1.job_id से अलग
print(job1.job_id == job2.job_id)  # False
Python 3.10+ — UUID के साथ Pydantic v2 model
from pydantic import BaseModel, Field
import uuid

class OrderEvent(BaseModel):
    event_id: uuid.UUID = Field(default_factory=uuid.uuid4)
    order_id: uuid.UUID
    status: str
    amount_cents: int

event = OrderEvent(
    order_id=uuid.UUID("a1c2e3f4-5b6d-4e7f-8c9d-0a1b2c3d4e5f"),
    status="payment_confirmed",
    amount_cents=4995,
)

print(event.model_dump_json(indent=2))
# {
#   "event_id": "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e",
#   "order_id": "a1c2e3f4-5b6d-4e7f-8c9d-0a1b2c3d4e5f",
#   "status": "payment_confirmed",
#   "amount_cents": 4995
# }
# Pydantic v2 uuid.UUID को automatically string में serialize करता है

Python में UUID v4 जेनरेट करते समय सामान्य गलतियाँ

मैंने इन चारों patterns को code reviews और production incidents में देखा है — इन्हें miss करना आसान है क्योंकि ये तुरंत कोई error नहीं उठाते।

Default के रूप में uuid4 को बिना Parentheses के कॉल करना

समस्या: uuid.uuid4 (function object) को dataclass या model में default_factory में wrap किए बिना default value के रूप में पास करना — Python class definition के समय एक बार default evaluate करता है, इसलिए हर instance एक ही UUID share करता है।

समाधान: Dataclasses में default_factory=uuid.uuid4 या Pydantic में Field(default_factory=uuid.uuid4) का उपयोग करें ताकि प्रत्येक instance के लिए नया UUID जेनरेट हो।

Before · Python
After · Python
@dataclass
class Session:
    # गलत: एक बार evaluate होता है, सभी instances यह UUID share करते हैं
    session_id: uuid.UUID = uuid.uuid4()
@dataclass
class Session:
    # सही: factory प्रति instance कॉल होती है
    session_id: uuid.UUID = field(default_factory=uuid.uuid4)
UUID ऑब्जेक्ट की Plain String से तुलना करना

समस्या: uuid.UUID ऑब्जेक्ट plain strings के बराबर नहीं होते, इसलिए session_id == '3b1f8a9d-...' हमेशा False return करता है, चाहे वैल्यू match करे — lookups silently टूट जाती हैं।

समाधान: हमेशा UUID की UUID से तुलना करें: तुलना से पहले string को uuid.UUID() से wrap करें, या दोनों sides को str() में बदलें।

Before · Python
After · Python
# वैल्यू match होने पर भी False return करता है
if record["session_id"] == "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e":
    revoke_session(record)
target = uuid.UUID("3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e")
if record["session_id"] == target:   # दोनों uuid.UUID हैं
    revoke_session(record)

# या boundary पर सब कुछ strings में normalize करें:
if str(record["session_id"]) == str(target):
    revoke_session(record)
.hex Store करना str() की जगह और Dashes खोना

समस्या: uuid_obj.hex एक 32-अक्षर की string produce करता है जिसमें hyphens नहीं होते। अगर downstream code canonical 36-अक्षर dashed format expect करता है (अधिकांश APIs और databases करते हैं), तो वह वैल्यू को reject या silently misparse करेगा।

समाधान: Canonical 36-अक्षर format के लिए str(uuid_obj) का उपयोग करें जब तक कि आपके पास compact hex form के लिए explicit requirement न हो।

Before · Python
After · Python
# "3b1f8a9d2c4e4f6a8b0d5e7c9f1a3d2e" स्टोर करता है — बिना dashes
payload = {"correlation_id": request_id.hex}
# "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e" स्टोर करता है — standard format
payload = {"correlation_id": str(request_id)}
UUID Expected होने पर random.random() या secrets.token_hex() का उपयोग

समस्या: random.random() क्रिप्टोग्राफ़िक रूप से सुरक्षित नहीं है, और secrets.token_hex(16) एक 32-अक्षर hex string produce करता है जो valid UUID नहीं है — downstream validators जो उस पर uuid.UUID() कॉल करते हैं, ValueError उठाएंगे।

समाधान: uuid.uuid4() का उपयोग करें जब receiving system UUID-formatted identifier expect करता हो। secrets.token_hex() का उपयोग केवल तब करें जब आपको explicitly एक random token चाहिए जो UUID-shaped न हो।

Before · Python
After · Python
import random, secrets

# UUID नहीं — uuid.UUID() validation में fail होगा
request_id = secrets.token_hex(16)   # "a1b2c3d4e5f6..."
session_id = str(random.random())    # "0.8273..." — बिल्कुल भी नहीं
import uuid

request_id = str(uuid.uuid4())  # "3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e"
# Valid UUID v4, क्रिप्टोग्राफ़िक रूप से सुरक्षित

Python में UUID जेनरेशन के तरीके — त्वरित तुलना

नीचे दिए गए सभी तरीके 128-बिट identifiers produce करते हैं लेकिन entropy source, privacy characteristics, और third-party install की ज़रूरत में अलग-अलग हैं।

मेथड
स्रोत
विशिष्टता
गोपनीयता-सुरक्षित
कस्टम प्रकार
गति
इंस्टॉल
uuid.uuid4()
Random (os.urandom)
2¹²² random bits
N/A
Standard
Built-in
uuid.uuid1()
Timestamp + MAC
Time + host
❌ (MAC उजागर)
N/A
Standard
Built-in
uuid.uuid3(name)
MD5 hash
Deterministic
namespace+name
Standard
Built-in
uuid.uuid5(name)
SHA-1 hash
Deterministic
namespace+name
Standard
Built-in
uuid_utils.uuid4()
Rust os.urandom
2¹²² random bits
N/A
~10× तेज़
pip install uuid-utils
secrets.token_hex(16)
os.urandom
128 random bits
N/A
Fast
Built-in
str(uuid.uuid4())
Random
2¹²² random bits
N/A
Standard
Built-in

Web applications, distributed systems, और database primary keys में सामान्य-उद्देश्य unique identifiers के लिए uuid.uuid4() का उपयोग करें जब sortability ज़रूरी न हो। uuid.uuid5() (या v3) का उपयोग deterministic IDs के लिए करें जो एक known namespace और name से derive होते हैं — उदाहरण के लिए, canonical URL के लिए stable ID जेनरेट करना। uuid_utils.uuid7() पर switch करें जब आपको database indexes के लिए time-ordered IDs चाहिए (उच्च insert rates पर B-tree indexes में page splits से बचता है)। uuid_utils.uuid4() का उपयोग करें जब raw generation throughput bottleneck हो।

UUID v4 बनाम UUID v7 — कौन सा उपयोग करें?

सबसे सामान्य व्यावहारिक प्रश्न यह है कि database primary keys के लिए UUID v4 या नया UUID v7 उपयोग करें। यहाँ संक्षिप्त उत्तर है: default में UUID v4 उपयोग करें; UUID v7 पर तभी switch करें जब index fragmentation एक measured समस्या हो।

UUID v4 values पूरी तरह random होती हैं, जिसका अर्थ है कि inserts B-tree index में random positions पर land करते हैं। moderate insert rates (सैकड़ों से कम हज़ार प्रति सेकंड) पर यह ठीक है — index buffer pool में fit होता है और random writes सस्ते होते हैं। बहुत अधिक insert rates पर, random placement frequent page splits और cache misses का कारण बनता है, write amplification बढ़ाता है और queries धीमी करता है।

UUID v7 most-significant bits में millisecond-precision Unix timestamp embed करता है, इसलिए समय के करीब insert किए गए rows index में भी करीब land करते हैं। यह B-tree indexes (PostgreSQL, MySQL, SQLite) को auto-increment integer जैसा behavior देता है: नए rows हमेशा index के अंत में append होते हैं, page splits eliminate होते हैं। Trade-off यह है कि UUID v7 timestamp encode करता है, जो creation time leak करता है — user-facing IDs के लिए इससे बचें जहाँ creation time sensitive है।

Python में, UUID v7 अभी standard library में नहीं है (Python 3.12 तक)। pip install uuid-utils से install करें और uuid_utils.uuid7() कॉल करें। यह uuid.UUID जैसा ही attribute set वाला ऑब्जेक्ट return करता है, इसलिए v4 से migration ID factory में एक-लाइन बदलाव है।

किसी भी Python setup के बिना one-click alternative के लिए, अपनी UUID string को UUID v4 generator और validator में paste करें — यह browser में सभी fields generate, validate, और decode करता है।

अक्सर पूछे जाने वाले प्रश्न

Python में UUID v4 कैसे जेनरेट करें?

Python के बिल्ट-इन uuid मॉड्यूल से uuid.uuid4() कॉल करें। यह एक UUID ऑब्जेक्ट लौटाता है — जब आपको टेक्स्ट प्रतिनिधित्व चाहिए तो str() से स्ट्रिंग में बदलें। यह मॉड्यूल standard library के साथ आता है इसलिए pip install की ज़रूरत नहीं।

Python
import uuid

session_id = uuid.uuid4()
print(session_id)           # जैसे 3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e
print(str(session_id))      # वही canonical स्ट्रिंग
print(session_id.hex)       # 3b1f8a9d2c4e4f6a8b0d5e7c9f1a3d2e (बिना dashes)

uuid.uuid4() और str(uuid.uuid4()) में क्या अंतर है?

uuid.uuid4() एक UUID ऑब्जेक्ट लौटाता है जिसमें .hex, .bytes, .int, और .version जैसे एट्रिब्यूट होते हैं। str(uuid.uuid4()) उस ऑब्जेक्ट को तुरंत 36-अक्षर की canonical स्ट्रिंग में बदल देता है, ऑब्जेक्ट को हटा देता है। ऑब्जेक्ट को तब रखें जब आपको कई प्रतिनिधित्व चाहिए; JSON payload, database, या HTTP header को वैल्यू पास करते समय boundary पर स्ट्रिंग में बदलें।

Python
import uuid

u = uuid.uuid4()
print(type(u))          # <class 'uuid.UUID'>
print(u.version)        # 4
print(u.hex)            # 32-char hex, बिना dashes
print(u.bytes)          # 16-byte binary
print(str(u))           # dashes के साथ canonical 36-char स्ट्रिंग

क्या uuid.uuid4() क्रिप्टोग्राफ़िक रूप से सुरक्षित है?

हाँ। Python का uuid.uuid4() आंतरिक रूप से os.urandom() का उपयोग करता है, जो ऑपरेटिंग सिस्टम के क्रिप्टोग्राफ़िक रूप से सुरक्षित random number generator (/dev/urandom Linux/macOS पर, Windows पर CryptGenRandom) से पढ़ता है। 122 random bits किसी भी व्यावहारिक workload के लिए collision की संभावना को नगण्य बनाते हैं। इसे random.random() से भ्रमित न करें, जो क्रिप्टोग्राफ़िक रूप से सुरक्षित नहीं है।

Python
import uuid, os

# uuid4 आंतरिक रूप से os.urandom(16) कॉल करता है
raw = os.urandom(16)
# uuid4 लौटाने से पहले version और variant bits सेट करता है
u = uuid.UUID(bytes=raw, version=4)
print(u)  # raw random bytes से valid v4 UUID

Python में यह कैसे जाँचें कि कोई स्ट्रिंग valid UUID v4 है?

uuid.UUID() से पार्स करें और .version एट्रिब्यूट जाँचें। अगर स्ट्रिंग valid UUID नहीं है, तो uuid.UUID() ValueError उठाता है — अमान्य इनपुट संभालने के लिए इसे catch करें। यह format (dashes, length) भी validate करता है।

Python
import uuid

def is_valid_uuid4(value: str) -> bool:
    try:
        u = uuid.UUID(value)
        return u.version == 4
    except ValueError:
        return False

print(is_valid_uuid4("3b1f8a9d-2c4e-4f6a-8b0d-5e7c9f1a3d2e"))  # True
print(is_valid_uuid4("not-a-uuid"))                              # False
print(is_valid_uuid4("3b1f8a9d-2c4e-1f6a-8b0d-5e7c9f1a3d2e"))  # False (v1, v4 नहीं)

Python से PostgreSQL या SQLite database में UUID कैसे स्टोर करें?

PostgreSQL के साथ (psycopg2 या asyncpg के ज़रिए), UUID ऑब्जेक्ट सीधे पास करें — driver इसे native UUID type में adapt करता है। SQLite के साथ, जिसमें native UUID type नहीं है, str(uuid_obj) से TEXT या uuid_obj.bytes से BLOB के रूप में स्टोर करें। SQLAlchemy में UUID column type है जो सभी dialects में इसे अपने आप handle करता है।

Python
import uuid
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE events (id TEXT PRIMARY KEY, name TEXT)")

event_id = uuid.uuid4()
conn.execute("INSERT INTO events VALUES (?, ?)", (str(event_id), "user_signup"))
conn.commit()

row = conn.execute("SELECT * FROM events").fetchone()
# स्टोर की गई स्ट्रिंग से UUID ऑब्जेक्ट फिर से बनाएं
retrieved_id = uuid.UUID(row[0])
print(retrieved_id.version)  # 4

क्या Python में एक साथ कई UUID जेनरेट किए जा सकते हैं?

हाँ — list comprehension या generator का उपयोग करें। uuid.uuid4() का हर कॉल स्वतंत्र होता है और एक अलग वैल्यू देने की गारंटी है। जहाँ throughput मायने रखती है, वहाँ bulk generation के लिए uuid-utils (Rust-backed) standard library से लगभग 10x तेज़ है।

Python
import uuid

# batch request के लिए 5 unique trace IDs जेनरेट करें
trace_ids = [str(uuid.uuid4()) for _ in range(5)]
for tid in trace_ids:
    print(tid)
# हर लाइन एक अलग UUID v4 है

संबंधित टूल्स

  • UUID v4 Generatorब्राउज़र में तुरंत UUID v4 वैल्यू जेनरेट करें — किसी Python environment की ज़रूरत नहीं। एक वैल्यू कॉपी करें या एक साथ सैकड़ों जेनरेट करें।
  • UUID v7 Generatortime-ordered UUID v7 वैल्यू जेनरेट करें — creation time के अनुसार sortable, database primary keys के लिए आदर्श जहाँ index fragmentation मायने रखती है।
  • UUID Decoderकिसी भी UUID को inspect करें — version, variant, timestamp (v1/v7), और node fields — बिना scratch से parser लिखे।
  • JWT DecoderJWT tokens को decode और inspect करें, जिनमें अक्सर UUID subject claims (sub) या jti identifiers session UUIDs के साथ होते हैं।
MS
Maria SantosBackend Developer

Maria is a backend developer specialising in Python and API integration. She has broad experience with data pipelines, serialisation formats, and building reliable server-side services. She is an active member of the Python community and enjoys writing practical, example-driven guides that help developers solve real problems without unnecessary theory.

DV
Dmitri Volkovतकनीकी समीक्षक

Dmitri is a DevOps engineer who relies on Python as his primary scripting and automation language. He builds internal tooling, CI/CD pipelines, and infrastructure automation scripts that run in production across distributed teams. He writes about the Python standard library, subprocess management, file processing, encoding utilities, and the practical shell-adjacent Python that DevOps engineers use every day.